Reputation: 137
alert("There will be an error")
[1, 2].forEach(alert)
Now if I run the code, only the first alert is shown and then we have an error! I know why we have an error (no Automatic semicolon insertion) but I don`t understand error message: Uncaught TypeError: Cannot read property '2' of undefined. How JavaScript interpreter read this code?
Upvotes: 2
Views: 86
Reputation: 2780
If you write JS without semicolons at the end of each line it will sometimes complain if you start a line with:
[
, (
, or any of the arithmetic operators +
, -
, *
, /
.
Explained further here: https://medium.com/@goatslacker/no-you-dont-need-semicolons-148d936b9cf2
So you can avoid this by defining an array as a variable.
alert("There will be an error")
var a = [1, 2]
a.forEach(alert)
Upvotes: 0
Reputation: 370729
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.
Upvotes: 7