0

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?

Ivan
  • 478
  • 2
  • 13
  • 1
    Check forEach syntax here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach – navnath Sep 29 '21 at 16:06
  • I think you are trying to bind your obj like `function printUser(value) { console.log(this.name+' is '+value+' years old'); } arr.forEach(printUser.bind(obj));` – navnath Sep 29 '21 at 16:15
  • 1
    `only function declaration` .. a function declared in expression context (eg. to the right of a `=` sign, inside `()` etc.) is a function expression. So **ONLY** function expressions can be used inside `forEach()` if you are writing a function literal (instead of a variable or function name) because the moment you put a function inside `()` it becomes an expression – slebetman Sep 29 '21 at 16:25
  • @slebetman _"a function declared in expression context (eg. to the right of a = sign, **inside () etc.**) is a function expression..."_ I can't agree with the part about `()`. I've just checked [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function#syntax). There's only one variant of function expression syntax – Ivan Sep 29 '21 at 16:41
  • May I ask, is there a reason why you're looking to do this? Or is it just out of interest? – OliverRadini Sep 30 '21 at 08:00
  • [The `let func =` is not part of the function expression](https://stackoverflow.com/a/69395145/1048572). – Bergi Nov 14 '21 at 07:42

2 Answers2

0

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);
phentnil
  • 2,195
  • 2
  • 14
  • 22
-1

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);
A_A
  • 1,832
  • 2
  • 11
  • 17