Home > Enterprise >  Can function expression be used in forEach method?
Can function expression be used in forEach method?

Time:09-30

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?

CodePudding user response:

So, it looks like we can use in forEach() method only function declaration and arrow function. Am I right or just missing something?

Like most "algol-like" languages, Javascript provides two distinct syntax entities: statements and expressions. The common rule is that while an expression can be a part of a statement, the opposite is not true, that is, you cannot use statements inside expressions (at least, not directly). Since function calls are expressions and let is a statement, someFunc(let x = ...) would be violation of that rule and hence a syntax error.

So, the conclusion would be "forEach (like any other function) only accepts expressions as arguments". This is not limited to "function declaration and arrow function", you can use arbitrary expressions, as long as the result is a function, e.g.

foo.forEach(some = (weird(), stuff()) ())

CodePudding user response:

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

  • Related