Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why provide an array argument in Javascript's array.forEach callback?

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);});
like image 954
Marcus Harrison Avatar asked Sep 16 '16 09:09

Marcus Harrison


1 Answers

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) {});
like image 102
redneb Avatar answered Sep 24 '22 02:09

redneb