'Why is array destructuring not working in this case?
I am trying to swap members of arr. But I am getting [0, 0] as output. I am expecting [1, 0].
const arr = [0, 1];
[arr[1],arr[0]] = arr;
console.log(arr)
But while doing this, it outputs [1, 0] which I think I understand.
const arr = [0, 1];
[arr[1],arr[0]] = [arr[0], arr[1]];
console.log(arr)
Solution 1:[1]
Your first example is both modifying the array arr points to and getting its values from that same array, as though you did this:
const arr = [0, 1];
// Here, `arr` is `[0, 1]`
arr[1] = arr[0]; // <=== Changes `arr[1]`...
// Now, `arr` is `[0, 0]`
arr[0] = arr[1]; // <=== ...so the new value of `arr[1]` is used here.
// Still `[0, 0]`
Your destructuring is doing the same thing: Using arr[1] after it's been changed by the destructuring assignment.
Your second example is modifying the array arr points to, but only after getting the old values from the array into a new array:
const arr = [0, 1];
const newArray = [arr[0], arr[1]];
// Here, `arr` is `[0, 1]`, `newArray` is `[0, 1]`
arr[1] = newArray[0]; // <=== Changes `arr[1]`...
// Here, `arr` is `[0, 0]`, `newArray` is still `[0, 1]`
arr[0] = newArray[1]; // <=== ...but that doesn't affect `newArray[1]`, so this works.
// Here, `arr` is `[1, 0]`, `newArray` is still `[0, 1]`
That works, because even though arr[1] was changed by the destructuring assignment, the new value for arr[0] isn't coming from arr[1], it's coming from newArray[1].
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
