This function reverses an array through de-structuring by reversing positions of elements in the array.
function reverseArray(arr){
for(let i=0; i < arr.length/2; i++){
// console.log('why does it fail')
[arr[i], arr[arr.length - i - 1]] = [arr[arr.length - i - 1], arr[i]]
}
return arr
}
console.log(reverseArray([1,2,3]))
It works well but if I un-comment the console.log line in the loop, it throws this error:
[arr[i], arr[arr.length - i - 1]] = [arr[arr.length - i - 1], arr[i]]
^
TypeError: Cannot set property '3' of undefined
If I move the log statement after the array destructure it works fine. I tried this in node 8.15.1, 11.3.0, & 12.2.0. What is causing this behavior?