Skip to content Skip to sidebar Skip to footer

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 questi

Solution 1:

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:

functionmy_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) {});

Solution 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 !

Post a Comment for "Why Provide An Array Argument In Javascript's Array.foreach Callback?"