When you have <expression>[...]
, the interpreter will attempt to look up a property on expression
. When the inside of the brackets contains commas, you're invoking the comma operator, which evaluates to the value of the last item in the list. So
foo[1, 2]
is equivalent to
foo[2]
That's exactly what's happening here:
alert("There will be an error")
[1, 2].forEach(alert)
equivalent to
alert("There will be an error")
[2].forEach(alert)
equivalent to
alert("There will be an error")[2].forEach(alert)
equivalent to (without the alert
message)
undefined[2].forEach(alert)
That's where the "2" comes from. alert
returns undefined
, so the error message is Uncaught TypeError: Cannot read property '2' of undefined
.
The [1, 2]
does not get evaluated as an array, even though it kind of looks like one.