Here's my example of code:
let arr = [18, 23, 44, 50];
let obj = {
name: 'Kate',
};
arr.forEach(let func = function(value) {
console.log(`${this.name} is ${value} years old`);
}, obj); //SyntaxError
So, it looks like we can use in forEach() method only function declaration and arrow function. Am I right or just missing something?
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);
You can use it without the assignment. The name (func) is optional.
let arr = [18, 23, 44, 50];
let obj = {
name: 'Kate',
};
arr.forEach(function func(value) {
console.log(`${this.name} is ${value} years old`);
}, obj);