Sub topic 3
What Your Callback Receives: Element, Index, and Array
This chapter assumes you can write arrow functions and know what a callback is from the earlier chapter on higher-order functions. Here the question is narrower. When map, filter, or reduce calls your function, which values does it pass in?
The Three Arguments
For map and filter, the method calls your callback once per element and passes three arguments, always in the same order:
- element: the current value.
- index: the position of that value in the array.
- array: the array the method was called on.
Your callback can declare as many of these as it needs. JavaScript does not complain when a function receives extra arguments it doesn't name, so n => n * 2 works because the index and array are passed and then ignored.
const letters = ['a', 'b', 'c'];
letters.map((element, index, array) => {
console.log(element, index, array);
return element;
});
// a 0 [ 'a', 'b', 'c' ]
// b 1 [ 'a', 'b', 'c' ]
// c 2 [ 'a', 'b', 'c' ]Using the Index
The index is useful whenever an element's position matters, for example when numbering items:
const steps = ['Install', 'Configure', 'Run'];
const numbered = steps.map((step, i) => `${i + 1}. ${step}`);
console.log(numbered); // ['1. Install', '2. Configure', '3. Run']With filter, the index lets you select elements by position:
const values = [10, 20, 30, 40, 50];
const everyOther = values.filter((_, i) => i % 2 === 0);
console.log(everyOther); // [10, 30, 50]The underscore is a convention for "I need this parameter's slot, but I don't use its value."
Using the Array Argument
The third argument lets the callback compare the current element with its neighbors or with the whole collection, without referring to an outer variable. That matters in a chain, where the intermediate array has no name:
const readings = [3, 7, 4, 9];
const changes = readings
.map(r => r * 10)
.map((value, i, arr) => (i === 0 ? 0 : value - arr[i - 1]));
console.log(changes); // [0, 40, -30, 50]In the second map, arr is the array that the first map returned, [30, 70, 40, 90]. The original readings array is not used at that step.
reduce Shifts Everything by One
reduce puts the accumulator first, so its callback receives four arguments:
| Position | map / filter | reduce |
|---|---|---|
| 1st | element | accumulator |
| 2nd | index | element |
| 3rd | array | index |
| 4th | (none) | array |
const weighted = [5, 5, 5].reduce((acc, n, i) => acc + n * i, 0);
console.log(weighted); // 0 + 5 + 10 = 15When Extra Arguments Bite
Because the method always passes all of these arguments, a function that already accepts an optional second parameter will treat the index as that parameter. Passing a function reference like .map(someFunction) is safe only if that function ignores its extra parameters. When you're not sure, wrap the call in an arrow function: .map(x => someFunction(x)). The pitfalls chapter shows the best-known example of this, map(parseInt).
Exercise
What does ['x', 'y', 'z'].filter((el, i, arr) => i === arr.length - 1) return, and why?
Show answer
It returns ['z']. The callback keeps an element only when its index equals the last valid index, arr.length - 1, which is 2. Only 'z' sits at index 2.
Exercise
Rewrite [2, 4, 6].reduce((acc, n) => acc + n, 0) so that each element is multiplied by its position (index) before it is added. What is the result?
Show answer
[2, 4, 6].reduce((acc, n, i) => acc + n * i, 0) returns 0*2 + 1*4 + 2*6 = 16. In reduce the index is the third parameter, because the accumulator comes first.