Sub topic 3
What Your Callback Receives: Element, Index, and Array
This chapter assumes you can write arrow functions, read array literals, and pass a function as an argument. You have already seen that map, filter, and reduce call a function you supply. Here the question is narrower: on each call, which arguments does that function receive, and what goes wrong if you ignore them?
The short answer is that the callback gets more than the current element. When you know the full argument list, you can use the index and the array itself on purpose, and you avoid bugs that come from passing in a function that expects different arguments.
The Three Arguments
For map, filter, and most other iteration methods (forEach, find, some, every, flatMap), the engine calls your callback with three arguments in a fixed order:
element: the value at the current position.index: the numeric position of that value.array: the array the method was called on.
You can see all three by logging them:
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' ]JavaScript does not check how many parameters a function declares. If your callback declares only element, the index and array are still passed and silently ignored. That leniency makes short callbacks like n => n * 2 possible. It also causes the arity bugs covered later in this chapter.
reduce Shifts Everything One Place Right
reduce adds the accumulator at the front, so its callback receives four arguments:
| Method | Callback arguments | Optional extra argument |
|---|---|---|
| `map` | `(element, index, array)` | `thisArg` |
| `filter` | `(element, index, array)` | `thisArg` |
| `forEach`, `find`, `some`, `every`, `flatMap` | `(element, index, array)` | `thisArg` |
| `reduce`, `reduceRight` | `(accumulator, element, index, array)` | `initialValue` |
The index in reduce has a detail that trips people up. Without an initial value, the first element becomes the starting accumulator, and the callback first runs at index 1:
const values = [10, 20, 30];
values.reduce((acc, n, i) => {
console.log('index', i);
return acc + n;
});
// index 1
// index 2
values.reduce((acc, n, i) => {
console.log('index', i);
return acc + n;
}, 0);
// index 0
// index 1
// index 2If your callback uses i to treat the first element specially, the version without an initial value never sees i === 0. A later chapter covers initial values in full. For now, keep in mind that the index tells you which element is current. It does not count how many times the callback has run.
Using the Index on Purpose
The index is useful whenever the output depends on position. Numbering items is the simplest case:
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 by position instead of by value:
const frames = ['f0', 'f1', 'f2', 'f3', 'f4'];
const everyOther = frames.filter((_, i) => i % 2 === 0);
console.log(everyOther); // ['f0', 'f2', 'f4']The underscore is a common convention for "I need this parameter's slot but not its value." Parameters are positional, so you cannot skip element to reach index. You must name something in the first slot.
Using the Array Argument
The third argument lets the callback look at other elements. A common use is comparing each value with its neighbor:
const readings = [10, 12, 9, 15];
const deltas = readings.map((value, i, arr) => (i === 0 ? 0 : value - arr[i - 1]));
console.log(deltas); // [0, 2, -3, 6]Another common use is removing duplicates by keeping only the first occurrence of each value:
const tags = ['js', 'css', 'js', 'html', 'css'];
const unique = tags.filter((tag, i, arr) => arr.indexOf(tag) === i);
console.log(unique); // ['js', 'css', 'html']When the array already has a variable name, as readings does, you could refer to that variable directly. The array argument matters most in chains, where the intermediate array has no name. Note that array is the array the current method was called on. In a chain, that is the previous step's output, not the original data:
const result = [5, 1, 4]
.filter(n => n > 1)
.map((n, i, arr) => n / arr.length);
console.log(result); // [2.5, 2]Here arr is [5, 4], the result of filter, so arr.length is 2 and not 3. Using the argument also keeps the callback self-contained. It works no matter which array it is attached to, which makes it easier to extract into a named function and reuse.
A reduce callback can use the array argument to finish a calculation on the last step. The example below computes an average in one pass:
const scores = [2, 4, 9];
const average = scores.reduce((acc, n, i, arr) => {
const sum = acc + n;
return i === arr.length - 1 ? sum / arr.length : sum;
}, 0);
console.log(average); // 5This works, but dividing the result of a plain sum (sum / scores.length) is usually easier to read. Use the array argument when it removes a step, not just because it is available.
Passing Named Functions: Arity Mismatch
Because every callback receives the index and array, passing an existing function by reference is only safe if that function ignores extra arguments. Functions with optional second parameters do not ignore them:
function formatPrice(amount, currency = 'USD') {
return `${amount.toFixed(2)} ${currency}`;
}
console.log([1, 2].map(formatPrice));
// ['1.00 0', '2.00 1']
console.log([1, 2].map(amount => formatPrice(amount)));
// ['1.00 USD', '2.00 USD']A default parameter applies only when the argument is undefined. The index 0 is not undefined, so currency becomes 0, then 1. The fix is the wrapper arrow, which passes only the arguments you choose. The well-known ['1', '2', '3'].map(parseInt) bug works the same way, with the index used as parseInt's radix. The pitfalls chapter covers it in detail.
The thisArg Parameter
map, filter, and the other non-reduce methods accept an optional second argument that becomes this inside the callback:
const scaler = {
factor: 3,
scale(n) {
return n * this.factor;
}
};
console.log([1, 2].map(scaler.scale, scaler)); // [3, 6]Without scaler as the second argument, this would be undefined in strict mode, and the call would throw. Arrow functions take this from the surrounding scope, so thisArg has no effect on them. reduce has no thisArg. Its second argument is the initial value. In modern code, a wrapper arrow such as .map(n => scaler.scale(n)) is clearer, and thisArg mostly shows up in older code.
Edge Cases: Mutation and Holes During Iteration
The array argument is a live reference to the array, not a copy. These methods decide how many indices to visit before the first callback runs, and then read each element at the moment they reach it:
const items = [1, 2, 3];
const seen = items.map((n, i, arr) => {
if (i === 0) {
arr.push(99); // appended: never visited
arr[2] = 30; // changed before it is reached: new value is seen
}
return n;
});
console.log(seen); // [1, 2, 30]
console.log(items); // [1, 2, 30, 99]The rules are:
- Elements added after iteration starts are not visited.
- Elements changed before they are reached are seen with their new values.
- Elements deleted before they are reached are skipped.
Results like this are hard to predict, so treat the array argument as read-only.
Holes in sparse arrays are also skipped. Holes are missing indices, which is different from indices that hold undefined:
const sparse = [1, , 3];
console.log(sparse.map((_, i) => i)); // [0, <1 empty item>, 2]The callback never runs for index 1, and map leaves the hole in its output. The common pitfalls chapter returns to sparse arrays.
Exercises
Exercise
What does ['a', 'b', 'c'].map((x, i, arr) => arr[arr.length - 1 - i] + i) return, and why?
Show answer
['c0', 'b1', 'a2']. For each index i, the callback reads the element at the mirrored position arr.length - 1 - i (2, 1, 0) and appends the index, so position and value come from different places in the same array.
Exercise
A teammate writes [4.5, 9.1].map(Math.round) and ['10', '20'].map(Number) and asks whether they are safe from the index-argument problem. Are they?
Show answer
Yes. Math.round and Number each use only their first argument and ignore the extra index and array, so both return the expected [5, 9] and [10, 20]. The danger is limited to functions whose second parameter changes their behavior, such as parseInt or a function with an optional default parameter.
Exercise
Inside [3, 7, 2].reduce((acc, n, i) => acc + i) with no initial value, which index values does the callback see, and what is the result?
Show answer
The callback sees indices 1 and 2, because the element at index 0 becomes the starting accumulator. It computes 3 + 1 = 4, then 4 + 2 = 6, so the result is 6.