Javascript's array iteration functions (forEach
, every
, some
etc.) allow you to pass three arguments: the current item, the current index and the array being operated on.
My question is: what benefits are there to operating on the array as an argument, vs. accessing it via the closure?
Why should I use this:
myArray.forEach(function(item, i, arr) {doSomething(arr);});
Instead of this:
myArray.forEach(function(item, i) {doSomething(myArray);});
It is possible that you want to pass a generic function as an argument to forEach
and not an anonymous function. Imagine a situation where you have a function defined like that:
function my_function(item, i, arr) {
// do some stuff here
}
and then use it on different arrays:
arr1.forEach(my_function);
arr2.forEach(my_function);
The third argument allows the function to know which array is operating on.
Another case where this might be usefull, is when the array has not been stored in a variable and therefore does not have a name to be referenced with, e.g.:
[1, 2, 3].forEach(function(item, i, arr) {});
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