10

This code generates an error when I run it with node v6.9.2

var req = {}

['foo', 'bar'].forEach(prop => {
    console.log("prop: " + prop)
});

The error is: TypeError: Cannot read property 'forEach' of undefined

Why would that be? There doesn't seem to be anything syntactically wrong with what I'm doing. I note that if I add a semi-colon after the var req = {} line the error disappears, but I still don't understand why since I thought semi-colons were optional in JavaScript as long as each statement was on a separate line.

1
  • Node 6.10.3 seems to work fine, just FYI Commented Jun 6, 2017 at 1:56

1 Answer 1

21

Automatic semicolon insertion has turned

var req = {}
['foo', 'bar']

into

var req = {}['foo', 'bar']

and of course {} doesn't contain a 'bar' property (because 'foo', 'bar' evaluates to 'bar').

(undefined).forEach(...) gets evaluated, which then leads to the error that you're seeing.


If you're relying on ASI, it's common practice to prefix lines beginning with [] or () with a semicolon:

var req = {}
;['foo', 'bar']
Sign up to request clarification or add additional context in comments.

1 Comment

Very interesting! I didn't know about ASI, and it's propagation effects. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.