Sub topic 7
How Array Method Callbacks Work
This chapter assumes you can write functions and arrow functions, and that you have used for...of and forEach from the previous chapter. Most of the array methods you will meet next (map, filter, reduce, find, sort) share one mechanism: you hand them a function, and they call it for you. If you understand that mechanism once, the methods themselves become easy to learn.
What a callback is
A callback is a function you pass as an argument to another function, which then calls it. You don't call it yourself. The array method decides when to call it, how many times, and with which arguments.
const prices = [4, 9, 2];
function logPrice(price) {
console.log('Price:', price);
}
prices.forEach(logPrice); // pass the function itself, do not call it
// Price: 4
// Price: 9
// Price: 2Notice logPrice with no parentheses. Writing prices.forEach(logPrice()) would call logPrice once with no argument and pass its return value (undefined) to forEach, which throws a TypeError because undefined is not a function.
The (element, index, array) signature
Every iteration method in this family calls your callback with the same three arguments:
| Position | Name (by convention) | Meaning |
|---|---|---|
| 1 | `element` | The current value |
| 2 | `index` | Its position in the array |
| 3 | `array` | The array the method was called on |
You can declare as many of these as you need. JavaScript doesn't complain if a function receives more arguments than it declares, so x => x * 2 simply ignores the index and array.
const letters = ['a', 'b', 'c'];
letters.forEach((letter, i, arr) => {
const isLast = i === arr.length - 1;
console.log(`${i}: ${letter}${isLast ? ' (last)' : ''}`);
});
// 0: a
// 1: b
// 2: c (last)The third argument is useful when the callback is defined somewhere else and has no other reference to the array. It also lets you look at neighboring elements:
const temps = [12, 15, 14, 18];
temps.forEach((t, i, arr) => {
if (i > 0) {
console.log(`Change at ${i}: ${t - arr[i - 1]}`);
}
});
// Change at 1: 3
// Change at 2: -1
// Change at 3: 4Two methods differ. reduce puts an accumulator first: (accumulator, element, index, array). sort calls a comparator with two elements, (a, b). Both get their own chapters.
What the method does with your return value
The calling pattern is shared, but each method reads the callback's return value differently. Most bugs with callbacks come from returning the wrong kind of value, or nothing at all.
| Method | Uses return value as | Stops early? |
|---|---|---|
| `forEach` | Ignored | No |
| `map` | The new element at that index | No |
| `filter` | Truthy keeps the element | No |
| `find` / `findIndex` | Truthy means "this is the one" | Yes, on first truthy |
| `some` | Truthy makes the result `true` | Yes, on first truthy |
| `every` | Falsy makes the result `false` | Yes, on first falsy |
| `reduce` | The next accumulator | No |
A common slip is using braces in an arrow function and forgetting return:
const nums = [1, 2, 3];
const wrong = nums.map(n => { n * 2; });
const right = nums.map(n => n * 2);
console.log(wrong); // [undefined, undefined, undefined]
console.log(right); // [2, 4, 6]With braces, the arrow body is a block and returns undefined unless you write return. Without braces, the expression's value is returned automatically.
The extra-argument trap
Because methods always pass three arguments, a function that accepts optional extra parameters can pick up values you didn't intend. The classic case is parseInt, whose second parameter is the radix (number base):
console.log(['1', '2', '3'].map(parseInt)); // [1, NaN, NaN]The calls actually made are parseInt('1', 0) (radix 0 means "guess", so 1), parseInt('2', 1) (radix 1 is invalid, so NaN), and parseInt('3', 2) (3 is not a binary digit, so NaN). The fix is to wrap the function so you control exactly which arguments it gets:
console.log(['1', '2', '3'].map(s => parseInt(s, 10))); // [1, 2, 3]
console.log(['1', '2', '3'].map(Number)); // [1, 2, 3]Number is safe because it uses only its first argument. The rule of thumb: pass a named function directly only if you know how it treats a second and third argument. Otherwise, wrap it in an arrow.
Callbacks run synchronously
Array methods call your callback immediately, one element after another, before the method returns. Nothing is scheduled for later.
console.log('before');
[1, 2].forEach(n => console.log('item', n));
console.log('after');
// before
// item 1
// item 2
// afterThis has a consequence for async callbacks. An async function returns a promise right away, and forEach ignores it, so the loop doesn't wait:
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
async function run() {
[300, 100].forEach(async ms => {
await wait(ms);
console.log('done', ms);
});
console.log('forEach returned');
}
run();
// forEach returned
// done 100
// done 300If you need to wait for each step, use a for...of loop with await. If the steps can run in parallel, use await Promise.all(arr.map(async ...)).
The optional thisArg
Most callback methods take a second argument, thisArg, which becomes this inside the callback. It only works with regular function callbacks. Arrow functions take this from the surrounding scope and ignore thisArg.
const limits = { max: 10 };
const a = [5, 12, 8].filter(function (n) {
return n <= this.max;
}, limits);
console.log(a); // [5, 8]In modern code you will rarely need this, because an arrow function that reads limits.max directly is clearer. You'll mostly see thisArg in older code.
Edge cases in how elements are visited
The methods follow precise rules when the array is unusual or changes during iteration.
The length is fixed when the method starts
forEach, map, filter, and similar methods read length once, before the first call. Elements you push during iteration are not visited:
const queue = [1, 2];
queue.forEach(n => {
if (n === 1) queue.push(99);
console.log(n);
});
// 1
// 2
console.log(queue); // [1, 2, 99]Values are read at visit time
If you change an element the method hasn't reached yet, the callback sees the new value. If you delete it or shorten the array, it is skipped.
const items = ['a', 'b', 'c'];
items.forEach((x, i, arr) => {
if (i === 0) arr[2] = 'C';
console.log(x);
});
// a
// b
// CHoles are skipped by most methods
A sparse array has missing indices. forEach, map, filter, some, every, and reduce don't call the callback for holes. find, findIndex, findLast, and findLastIndex do visit them, as undefined.
const sparse = [1, , 3];
let calls = 0;
sparse.forEach(() => calls++);
console.log(calls); // 2
let findCalls = 0;
sparse.find(() => { findCalls++; return false; });
console.log(findCalls); // 3The Edge Cases chapter covers sparse arrays in more detail. For now, remember that "once per element" really means "once per index that exists," except in the find family.
Exercise
What does ['10', '10', '10'].map(parseInt) print, and why? Rewrite it so it returns [10, 10, 10].
Show answer
It prints [10, NaN, 2]. map passes the index as the second argument, which parseInt treats as the radix: parseInt('10', 0) is 10, parseInt('10', 1) is NaN because radix 1 is invalid, and parseInt('10', 2) is 2 (binary). Fix it with ['10', '10', '10'].map(s => parseInt(s, 10)) or .map(Number).
Exercise
Using only the callback's arguments (no outer variables), write a filter call that keeps the elements of [3, 3, 5, 7, 7, 7, 2] that differ from the element just before them. The first element should always be kept.
Show answer
[3, 3, 5, 7, 7, 7, 2].filter((x, i, arr) => i === 0 || x !== arr[i - 1]) returns [3, 5, 7, 2]. The index and array arguments let the callback compare each element with its neighbor.
Exercise
This code is meant to double each number, but result is [undefined, undefined, undefined]. Explain the bug and fix it: const result = [1, 2, 3].map(n => { n * 2 });
Show answer
The arrow body uses braces, so it is a block with no return statement and each call returns undefined. map stores those values. Fix it with n => n * 2 or n => { return n * 2; }.
Exercise
How many times is the callback called in const a = [1, 2, 3]; a.forEach(x => { a.push(x); });, and what is a afterward?
Show answer
Three times. forEach reads length (3) before it starts, so the pushed elements are not visited. Afterward a is [1, 2, 3, 1, 2, 3].