12

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);});
1
  • If you want to pass array as argument, why wrap it in .forEach in the first place? Commented Sep 16, 2016 at 9:58

2 Answers 2

22

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) {});
Sign up to request clarification or add additional context in comments.

Comments

-2

there is many cases in real life where knowing where an error is occuring and what was the content of your array. And focusly in a backend JS context like a NodeJS application..

Imagine your website is attacked, you want to know how your pirats are looking to enter into your website, in that case providing the array which contained the entire elements is useful. Look at the ECMASCRIPT 2020 page 642-643 it is written

callbackfn is called with three arguments: 
the value of the element,
the index of the element,
and the object being traversed

illustration : callbackfn is called with three arguments: the value of the element, the index of the element, and
the object being traversed Ecmascript 2020 manual

ok try this example

let myArray = [2 , 3, 5 , 7 , "ഊമ്പി", 13]
let foo = null
myArray.forEach(function(value, index, currentObject) {
    try {
        foo = 3.14*value;
        if (Number.isNaN(foo)) throw "foo is NaN" 
    } 
    catch (error) {
        console.error(error + ", and value: " + value + ", index: " + index + ", currentObject: " + currentObject);
    }
});

Hope that answer will help newbies That's all folk's !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.