Skip to content

What is the reason array is available inside reduce(), map(), etc.?

In the following example, we have access to the array as numbers and arr. It seems more in line with functional programming to use the internal variable arr but what is an explicit reason why we should use it instead of the exterior variable, since, numbers and arr are both pointers to the same array value anyway.

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, m, index, arr) => {
    console.log(`acc=${acc}, m=${m}, index=${index}, arr=${arr}`);
    console.log(`acc=${acc}, m=${m}, index=${index}, numbers=${numbers}`);
    return acc += m;
}, 100);
console.log(sum);

Answer

Because not every array will be stored in a variable. You can chain calls to map() & other, or after a call to a function that returns an array, in those cases you can access the array by variable name.

functionThatReturnsAnArray(...).map((acc, m, index, arr) => {
    // We can only access the array because 
    //it was passed as an argument to the anonymous function
})