13

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?

2
  • 3
    From functional-programming point of view, it lets you keep the purity of the function. Commented Apr 19, 2017 at 15:46
  • 3
    I suppose it could be for a reference to an array literal that is not stored in a variable. [1,2,3].forEach(function (elem, index, arrayReference) { ... }); Commented Apr 19, 2017 at 15:48

2 Answers 2

23

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Well ok, the function knows about the array, but for what purpose?
@mortb The callback might need values from other cells in the array while processing each individual cell. It may want to know the length of the array. The array may have additional non-numeric properties that are required for doing what the callback does. There are many, many reasons. I don't think I would say it's common, but it definitely happens sometimes.
5

The callback need not be in the same scope as the forEach call. In a case like this, the third parameter would ensure that the callback has some reference to that array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.