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?
var arr = [1, 2, 3][arr[2], arr[1], arr[0]] = arr;, which tries to accessarr[2]beforearr’s initialization is finished. See also the documentation which has a note about semicolons.[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. Hence1, 2, 1.const arrReversed = arr.slice().reverse();. Usearr.slice();if you want to reversearrin place.