What is the third parameter for a forEach callback function in JavaScript
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
both array
are the same arrays and arr
exist in the closure of the callback function.
Now the question is, what is the point of passing array
the callback function?
If your callback function was declared elsewhere:
function forEachCallback(value, i, array) {
// ...
}
Then he doesn't know which array he is using for:
someArray(forEachCallback);
Since the array is passed as the last argument, such a callback has access to it.
The callback does not have to be in the same scope as the call forEach
. In such a case, the third parameter ensures that the callback has some reference to that array.