2

I'm trying to learn swapping the elements in the array using destructuring concepts in javascript.

var arr = [1, 2, 3]
[arr[2], arr[1], arr[0]] = arr
console.log(arr);

I thought the console will print [3, 2, 1].

But it came error like

TypeError: Cannot read properties of undefined (reading '2')

I don't need an alternative method to get output, I want to learn that why undefined error came?

3
  • 5
    Use semicolons. Your first statement is var arr = [1, 2, 3][arr[2], arr[1], arr[0]] = arr;, which tries to access arr[2] before arr’s initialization is finished. See also the documentation which has a note about semicolons. Commented Jun 10, 2023 at 14:05
  • 1
    As @SebastianSimon said. And this will not work as expected since the array overwrites itself. The result will be [1, 2, 1]. The last element (3) is overwritten with 1, Then the second element is overwritten with 2. Lastly the first element is overwritten with the last element which is now 1. Hence 1, 2, 1. Commented Jun 10, 2023 at 14:08
  • You can use AST explorer to see how the code is interpreted. If you simply want to reverse an array, use const arrReversed = arr.slice().reverse();. Use arr.slice(); if you want to reverse arr in place. Commented Jun 10, 2023 at 14:11

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.