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