0

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?

  • 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](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#binding_and_assignment) which has a note about semicolons. – Sebastian Simon Jun 10 '23 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`. – Sani Huttunen Jun 10 '23 at 14:08
  • You can use [AST explorer](//astexplorer.net/) 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_. – Sebastian Simon Jun 10 '23 at 14:11

0 Answers0