Sub topic 7
How Array Method Callbacks Work
This chapter assumes you know how to write functions and arrow functions, and that you can loop over an array with for...of or forEach. Methods such as map, filter, find, and some all rely on the same mechanism, so learning it once makes each of those methods easier to pick up.
What a callback is
A callback is a function you pass to another function, which then calls it for you. When you pass a callback to an array method, the method loops over the array and calls your function once for each element. You write only the logic for a single element.
const scores = [90, 75, 82];
scores.forEach((score, index, arr) => {
console.log(`${index + 1}/${arr.length}: ${score}`);
});
// 1/3: 90
// 2/3: 75
// 82 is printed last as 3/3: 82The (element, index, array) signature
Every call passes the callback three arguments, in this order:
element: the current value.index: its position in the array.array: the whole array the method was called on.
You can declare only the parameters you need. JavaScript ignores any extra arguments. The index and array parameters are useful when a result depends on an element's neighbours:
const scores = [90, 75, 82];
const changes = scores.map((s, i, arr) => (i === 0 ? 0 : s - arr[i - 1]));
console.log(changes); // [0, -15, 7]You can also pass a named function instead of an inline arrow function. Pass the function itself, without parentheses:
function isPassing(score) {
return score >= 80;
}
console.log([90, 75, 82].filter(isPassing)); // [90, 82]What the return value means
The callback's signature is the same across these methods, but each method uses the callback's return value in its own way:
| Method | How the return value is used |
|---|---|
| `forEach` | Ignored |
| `map` | Becomes the element at the same position in the new array |
| `filter` | Truthy keeps the element |
| `find`, `findIndex` | Truthy stops the search at this element |
| `some`, `every` | Truthy or falsy decides the boolean result |
reduce uses a different signature: (accumulator, element, index, array). Its chapter covers it in detail.
The extra-arguments trap
Because the method always passes three arguments, a function that accepts optional parameters can receive values you did not intend. parseInt(string, radix) is the classic case:
console.log(['1', '2', '3'].map(parseInt)); // [1, NaN, NaN]
console.log(['1', '2', '3'].map(s => parseInt(s, 10))); // [1, 2, 3]In the first line, the index goes in as the radix. The calls are parseInt('2', 1) and parseInt('3', 2), and both return NaN. When you pass a function you did not write yourself, wrap it in an arrow function that forwards only the arguments you mean to pass.
Exercise
What does ['10', '10', '10'].map(parseInt) return, and why?
Show answer
[10, NaN, 2]. map passes the index as parseInt's radix. parseInt('10', 0) treats radix 0 as base 10 and returns 10. parseInt('10', 1) returns NaN because radix 1 is invalid. parseInt('10', 2) reads '10' as binary and returns 2.
Exercise
Use map with the index parameter to turn ['a', 'b', 'c'] into ['0:a', '1:b', '2:c'].
Show answer
['a', 'b', 'c'].map((letter, i) => ${i}:${letter})