'Cannot read property 'forEach' of undefined

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.



Solution 1:[1]

Keep the semi-colon so the variable declaration of funcs does not include the anonymous array you instantiate as belonging to the variable and also, if you are simply trying to push all the elements of the array into 'funcs' then it should look like:

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

Solution 2:[2]

we called the forEach method on an undefined value, we got the error.

    const myarr = undefined;

//  Initialize to empty array if falsy
const arr = myarr || [];

//  Using optional chaining
arr?.forEach(element => {
  console.log(element);
});

//  Check if truthy
if (arr) {
  arr.forEach(element => {
    console.log(element);
  });
}

//  Check if Array
if (Array.isArray(arr)) {
  arr.forEach(element => {
    console.log(element);
  });
}

Solution 3:[3]

Another solution to this problem is to avoid using anonymous array. No semicolons needed.

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

Solution 4:[4]

Add semi-colon in the of first line

var funcs = []; //<-- ; semi-colon added here
[1, 2].forEach( (i) => funcs.push( () => i  ) )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 maxwell
Solution 2 Avnish Jayaswal
Solution 3 Sylwek
Solution 4 fct