6

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)

3
  • 7
    The destructuring assignment is modifying the array. arr[1] becomes 0, and then so does arr[0] Commented Apr 20, 2022 at 15:31
  • What are you trying to do? The code you posted is weird and doesn't make a lot of sense. Commented Apr 20, 2022 at 15:33
  • @Utshav - I had the array indexes backward in my answer, which may have made it hard to understand. I've fixed them. Commented Apr 21, 2022 at 6:34

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.