skip to Main Content

I forgot a comma initializing a 2D array in javascript and, to my surprise, it compiled. E.g.:

amIMissingSomething = [
    [1, 2, 3]
    [4, 5, 6],
    [7, 8, 9]
]

console.log(amIMissingSomething) // [undefined, [7, 8, 9]]

I expected a syntax error to occur. However, after a whole lot of time, I learned this is valid javascript and evaluates to: [undefined, [7, 8, 9]]. What’s going on here?

2

Answers


  1. It is getting parsed as:

    amIMissingSomething = [
        [1,2,3][4,5,6],
        [7,8,9]
    ]
    

    the comma operator returns the last expression so basically:

    amIMissingSomething = [
        [1,2,3][6],
        [7,8,9]
    ]
    

    and since the first array doesn’t have 7 elements it evaluates to undefined

    Login or Signup to reply.
  2. It’s interpreted as array[index]

    See property accessor

    const a = [1, 2, 3][0]
    
    console.log(a)

    The result of expession 4, 5, 6 is 6, see comma operator

    const arrayChangeHandler = {
      get: function(target, property) {
        console.log('getting ' + property + ' for ' + target);
        return target[property];
      },
    };
    
    const originalArray = [1, 2, 3];
    const proxyToArray = new Proxy( originalArray, arrayChangeHandler );
    
    proxyToArray[4, 5, 6]
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search