Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Cannot read property 'forEach' of undefined Javascript

Following is the code in which I am getting Cannot read property 'forEach' of undefined.

const print2 = function(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )

Let me know what I am doing wrong here, though if I do -

function print2(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )

this is working fine.

enter image description here

like image 599
Nesh Avatar asked Nov 29 '22 21:11

Nesh


1 Answers

Since there's no semicolon after the function, the snippet gets interpreted as the following:

const print2 = function(x, y) {
  console.log(x*y)
}[1,2,3,4].forEach( x => print2(x, 20) )

Which means that it's trying to index into the function. Add a semicolon either after the function, or before the array literal:

const print2 = function(x, y) {
  console.log(x*y)
};

[1,2,3,4].forEach( x => print2(x, 20) )

or

const print2 = function(x, y) {
  console.log(x*y)
}

;[1,2,3,4].forEach( x => print2(x, 20) )

More about Javascript's automatic semicolon insertion here: What are the rules for JavaScript's automatic semicolon insertion (ASI)?

like image 183
cbr Avatar answered Dec 04 '22 08:12

cbr