Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  13] [ 5]  / answers: 1 / hits: 34680  / 4 Years ago, thu, may 28, 2020, 12:00:00

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


More From » node.js

 Answers
24

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


[#50913] Monday, May 18, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kayden

Total Points: 546
Total Questions: 102
Total Answers: 95

Location: Virgin Islands (U.S.)
Member since Fri, Mar 4, 2022
2 Years ago
;