I recently noticed that when using array.prototype.map(), my callback function may accept a third argument which is the array I'm mapping. I wonder if there are any use cases for this argument because inside the callback function, the array can be accessed anyways.
If I access the array I'm mapping inside the callback function, why/when should I rather use the third argument instead of just accessing the array?
example
Even though both methods should work fine in every use case I can imagine, I'd like to know which is the recommended way to do it and why.
The third argument can be useful when you are chaining several array methods and need to access the intermediate state of the array (result of the previous operation):
const source = [-3,-2,-1,0,1,2,3,4,5];
source
.filter(n => n >= 0)
.map((n, index, arr) => {
// arr contains only non-negative numbers
// here you may have some logic that rely on it
return n;
})
EDIT: This answer was already (coincidentally) given in the flagged dupe. Check it out over there.
You may wish to reference the original array in a generic fashion. For instance, the callback may be a separate function, not just an anonymous one as is usually seen:
function arrayMapper(val, idx, arr) {
// Some operations which use arr
}
myArray.map(arrayMapper);
myOtherArray.map(arrayMapper);
Note how each in execution of arrayMapper, the arr parameter refers to a different array in the outer scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With