Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is point of third parameter in forEach callback function in JavaScript [duplicate]

I know that forEach in JavaScript calls my callback function with three parameters:

arr.forEach(function callback(currentValue, index, array) {
    //your iterator
})

In the above example arr and array are same array and arr exists in the callback function closure.

Now the question is what is the point of passing array to the callback function?

like image 357
Arashsoft Avatar asked Apr 19 '17 15:04

Arashsoft


1 Answers

If your callback function were declared elsewhere:

function forEachCallback(value, i, array) {
  // ...
}

Then it has no idea what array it's being used for:

someArray.forEach(forEachCallback);

Because the array is passed as the last argument, such a callback has access to it.

like image 146
Pointy Avatar answered Oct 26 '22 01:10

Pointy