Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'forEach' of undefined

Tags:

javascript

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

Why does it produce the error below?

TypeError: Cannot read property 'forEach' of undefined     at Object.<anonymous> 

However, the error goes away if the semicolon ; is added to the end of the first line.

like image 244
sof Avatar asked Aug 12 '16 00:08

sof


People also ask

Can not read the property forEach of undefined?

The "Cannot read property 'forEach' of undefined" error occurs when calling the forEach method on an undefined value. To solve the error make sure to initialize the variable to the correct value and only call the forEach method on the correct data type.

What does Cannot read property of undefined mean?

What Causes TypeError: Cannot Read Property of Undefined. Undefined means that a variable has been declared but has not been assigned a value. In JavaScript, properties and functions can only belong to objects.

What is the difference between MAP and forEach?

Differences between forEach() and map() methods:The forEach() method does not create a new array based on the given array. The map() method creates an entirely new array. The forEach() method returns “undefined“. The map() method returns the newly created array according to the provided callback function.

Can not read property value of null?

The "Cannot read property 'value' of null" error occurs when: trying to access the value property on a null value, e.g. after calling getElementById with an invalid identifier. inserting the JS script tag before the DOM elements have been declared.


1 Answers

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).

like image 123
rvighne Avatar answered Sep 25 '22 06:09

rvighne