Cannot read property ‘forEach’ of undefined

There is no semicolon at the end of the first line. So the two lines run together, and it is interpreted as setting the value of funcs to

[][1, 2].forEach( (i) => funcs.push( () => i  ) )

The expression 1, 2 becomes just 2 (comma operator), so you’re trying to access index 2 of an empty array:

[][2] // undefined

And undefined has no forEach method. To fix this, always make sure you put a semicolon at the end of your lines (or if you don’t, make sure you know what you’re doing).

Leave a Comment