Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 629
Tsubasa Yamaguchi Avatar asked Dec 18 '22 18:12

Tsubasa Yamaguchi


2 Answers

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.

like image 105
Nathan Avatar answered Dec 27 '22 19:12

Nathan


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

like image 35
thinke Avatar answered Dec 27 '22 19:12

thinke