Tsubasa Yamaguchi
Tsubasa Yamaguchi

Reputation: 175

How to use arrow function in forEach?

I am studying about arrow function in Javascript.
I used forEach in two ways.
The one without arrow is working, but the one with arrow is not working.

Could you please let me know why?

    let ary = [1,2,3,4,5];

    function callback (i) {
        console.log(i);
    }

    // Working
    ary.forEach(callback);

    // Not working
    ary.forEach((i)=>callback);

Upvotes: 6

Views: 17334

Answers (2)

thinke
thinke

Reputation: 311

you can use:

ary.forEach(i=>callback);

But you'd better use arrow function in this way,and there is no need to define function callback

let ary = [1,2,3,4,5];

ary.forEach(i=>{
  console.log(i);
});

Arrow functions like anonymous functions. That's an array function,and i is the param.

i=>{
  console.log(i);
}

You can learn more from there Array Functions

Upvotes: 5

Nathan
Nathan

Reputation: 12010

In the "non-working" code, you're passing a function that returns a function (callback) to forEach. callback itself is never called.

This would actually call the function, but it is basically the same as directly passing callback directly to forEach as in your first example:

ary.forEach((i) => callback(i));

Please see the documentation for arrow functions.

Upvotes: 8

Related Questions