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]
.