0

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?

Todd
  • 652
  • 2
  • 19
  • 37
  • 1
    Always use semicolons unless you're *absolutely certain* of what you're doing, and even then, omitting them can easily trip you up. Your code evaluates to `undefined[arr[i], arr[arr.length - i - 1]]` -> `undefined[3]` – CertainPerformance Jul 19 '19 at 21:09
  • @CertainPerformance adding the semi colons does correct the behavior. But I don't understand why. – Todd Jul 19 '19 at 21:11
  • 2
    Because there's no semicolon, the `[` on the next line is interpreted as part of the same statement. See the linked question - a semicolon does not automatically get inserted. – CertainPerformance Jul 19 '19 at 21:11
  • @Todd http://inimino.org/~inimino/blog/javascript_semicolons – Bergi Jul 19 '19 at 21:14

0 Answers0