Using let
, var
, or const
where a callback function is expected is the SyntaxError
. You could drop let
and the code will run fine or you could declare the function outside of forEach
and call it within forEach
as follows:
let func = function(value) {
console.log(`${this.name} is ${value} years old`);
};
arr.forEach(func, obj);
In the code below, I show the original code you provided without the let
keyword in the forEach
call to show that it works. I also added the suggested function declaration and the corresponding forEach
call.
let arr = [18, 23, 44, 50];
let obj = {
name: 'Kate',
};
console.log('\tfunc');
arr.forEach(func = function(value) {
console.log(`${this.name} is ${value} years old`);
}, obj);
console.log('\tfunc2');
let func2 = function(value) {
console.log(`${this.name} is ${value} years old`);
};
arr.forEach(func2, obj);