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
It is getting parsed as:
the comma operator returns the last expression so basically:
and since the first array doesn’t have 7 elements it evaluates to
undefined
It’s interpreted as
array[index]
See property accessor
The result of expession
4, 5, 6
is 6, see comma operator