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);
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With