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.
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 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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With