Sub topic 3
Synchronous Callbacks: map, filter, forEach, and Your Own Higher-Order Functions
This chapter assumes you can write functions and arrow functions, work with arrays and objects, and run scripts in Node.js or a browser console. You should also know from the previous chapter that a callback is a function you pass to another function so that function can call it.
A synchronous callback is one that the receiving function calls before it returns. All the work happens while the receiving function is still on the call stack. Nothing is deferred and nothing waits. This chapter shows how that works in the built-in array methods, covers the mistakes intermediate developers commonly make with them, and shows you how to write your own higher-order functions.
Higher-Order Functions
A higher-order function either takes a function as an argument, returns a function, or does both. Array.prototype.map takes a function. A function that builds and returns a configured function is also higher-order. In this chapter, "higher-order function" means the first kind: a function that receives a callback and calls it.
Here is the smallest useful example:
function repeat(times, callback) {
for (let i = 0; i < times; i++) {
callback(i);
}
}
repeat(3, (n) => console.log('call', n));
// call 0
// call 1
// call 2
const doubled = [1, 2, 3].map((x) => x * 2);
console.log(doubled); // [2, 4, 6]repeat calls callback three times inside its own loop. When repeat returns, every call has already finished. map works the same way: by the time doubled is assigned, the arrow function has run once for each element.
What "Synchronous" Means in Practice
Because the callback runs inside the caller's execution, code after the higher-order call always sees the finished result. Log statements show the ordering clearly:
console.log('before');
[1, 2, 3].forEach((x) => console.log('item', x));
console.log('after');
// before
// item 1
// item 2
// item 3
// afterThe following diagram shows the call stack during a map call. Each callback invocation is pushed on top of map and popped off before map moves on.
Two practical consequences follow from this model:
- Exceptions thrown inside the callback travel up through the higher-order function to your code, so an ordinary
try/catcharound the call catches them. - A long-running callback blocks everything else. A
mapover a million items with an expensive callback freezes a browser tab until it finishes.
try {
[1, 2, 3].forEach((x) => {
if (x === 2) throw new Error('bad item: ' + x);
console.log('ok', x);
});
} catch (err) {
console.log('caught:', err.message);
}
// ok 1
// caught: bad item: 2The try/catch works here because the throw happens while forEach is still on the stack. Asynchronous callbacks behave differently, as the next chapter shows.
The Built-In Array Methods
Every iteration method on arrays takes a callback. They differ in what they do with the callback's return value and in whether they stop early.
| Method | Callback arguments | What the return value means | Method returns | Stops early |
|---|---|---|---|---|
| `forEach` | element, index, array | Ignored | `undefined` | No |
| `map` | element, index, array | New element | New array, same length | No |
| `filter` | element, index, array | Truthy keeps the element | New array | No |
| `find` / `findIndex` | element, index, array | Truthy means "this one" | Element / index, or `undefined` / `-1` | Yes, on first truthy |
| `some` | element, index, array | Truthy means a match | `true` or `false` | Yes, on first truthy |
| `every` | element, index, array | Falsy means a failure | `true` or `false` | Yes, on first falsy |
| `reduce` | accumulator, element, index, array | Next accumulator | Final accumulator | No |
| `sort` | a, b | Negative, zero, or positive ordering | The same array, sorted in place | No |
A short example that chains several of them:
const orders = [
{ id: 1, total: 40, paid: true },
{ id: 2, total: 15, paid: false },
{ id: 3, total: 90, paid: true },
];
const paidTotals = orders
.filter((o) => o.paid)
.map((o) => o.total);
const revenue = paidTotals.reduce((sum, t) => sum + t, 0);
const hasLargeOrder = orders.some((o) => o.total > 50);
const firstUnpaid = orders.find((o) => !o.paid);
console.log(paidTotals); // [40, 90]
console.log(revenue); // 130
console.log(hasLargeOrder); // true
console.log(firstUnpaid); // { id: 2, total: 15, paid: false }Each method runs its callback to completion before the next method in the chain starts. filter builds a full intermediate array, then map walks that array. On huge arrays this costs memory. A single reduce or a plain loop can avoid the intermediate array if that matters.
Common Errors
Passing a function that expects different arguments
The array methods pass three arguments: element, index, and array. If the callback you hand over uses a second parameter for something else, it receives the index anyway.
console.log(['1', '2', '3'].map(parseInt));
// [1, NaN, NaN]parseInt(string, radix) receives the index as its radix. parseInt('2', 1) is NaN because radix 1 is invalid, and parseInt('3', 2) is NaN because 3 is not a binary digit. Wrap the function so you control 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 here because it uses only its first argument. The general rule is to wrap any function you didn't write when you pass it as a callback, unless you know its full parameter list. A library update that adds an optional second parameter can silently break arr.map(libFn).
Forgetting to return from the callback
An arrow function with a block body needs an explicit return. Without it, map fills the array with undefined and filter drops everything.
const wrong = [1, 2, 3].map((x) => { x * 2; });
console.log(wrong); // [undefined, undefined, undefined]
const right = [1, 2, 3].map((x) => x * 2);
console.log(right); // [2, 4, 6]Returning an object literal from a concise arrow needs parentheses: (x) => ({ value: x }). Without them, the braces are read as a function body.
Trying to break out of forEach
return inside a forEach callback only ends that one callback call. forEach keeps going. break is a syntax error inside the callback. If you need to stop early, use the method whose job that is (some, every, find), or use a for...of loop.
const nums = [3, 8, 12, 5];
// Continues through every element; return only skips the log
nums.forEach((n) => {
if (n > 10) return;
console.log('forEach saw', n);
});
// forEach saw 3, forEach saw 8, forEach saw 5
// Stops at the first match
for (const n of nums) {
if (n > 10) break;
console.log('for...of saw', n);
}
// for...of saw 3, for...of saw 8Using map for side effects
map returns a new array. If you ignore that array and use map only to run side effects, switch to forEach. That makes the intent clear and avoids allocating an array nobody reads.
Sorting without a comparator
The default sort converts elements to strings and compares them in UTF-16 code unit order.
console.log([10, 9, 1].sort()); // [1, 10, 9]
console.log([10, 9, 1].sort((a, b) => a - b)); // [1, 9, 10]The comparator must be consistent. If it returns random values, or returns true/false instead of a number, the result depends on the engine. sort also mutates the array. Use toSorted (ES2023) or copy first with [...arr].sort(...) when you need the original order kept.
Edge Cases Worth Knowing
The iteration range is fixed at the start
forEach, map, and the others read the array's length once, before the first callback. Elements you append during iteration are not visited. Elements you delete before they are reached are skipped.
const arr = [1, 2, 3];
arr.forEach((x) => {
if (x === 1) arr.push(99);
console.log(x);
});
// 1, 2, 3
console.log(arr); // [1, 2, 3, 99]This behavior is defined by the spec, but code that mutates the array it iterates over is hard to read. Build a new array instead.
Holes in sparse arrays are skipped
Array methods skip missing indices. A for loop or for...of visits them as undefined.
const sparse = [1, , 3];
sparse.forEach((x, i) => console.log(i, x));
// 0 1
// 2 3
for (const x of sparse) console.log(x);
// 1, undefined, 3Array(3).map((_, i) => i) returns an array of three holes, not [0, 1, 2], because there are no elements for the callback to run on. Use Array.from({ length: 3 }, (_, i) => i) instead.
reduce without an initial value
When you leave out the initial value, reduce uses the first element as the starting accumulator. On an empty array it throws a TypeError. Always pass an initial value unless you know the array is non-empty.
console.log([].reduce((a, b) => a + b, 0)); // 0
// [].reduce((a, b) => a + b); // TypeError: Reduce of empty array with no initial valueWriting Your Own Higher-Order Functions
Writing your own versions of the built-ins shows you what they do. The calling convention is part of the contract: what arguments the callback receives, in what order, and what its return value means.
function myMap(array, callback) {
if (typeof callback !== 'function') {
throw new TypeError('callback must be a function');
}
const result = new Array(array.length);
for (let i = 0; i < array.length; i++) {
if (i in array) {
result[i] = callback(array[i], i, array);
}
}
return result;
}
function myFilter(array, predicate) {
const result = [];
for (let i = 0; i < array.length; i++) {
if (i in array && predicate(array[i], i, array)) {
result.push(array[i]);
}
}
return result;
}
console.log(myMap([1, 2, 3], (x, i) => x * 10 + i)); // [10, 21, 32]
console.log(myFilter([5, 12, 8, 20], (x) => x > 10)); // [12, 20]Some design choices are visible in this code:
- The function checks the callback's type at the start. A bad argument fails at the call site with a clear message, before any work is done.
- The
i in arraycheck matches the built-in handling of holes. - The callback receives
(element, index, array), matching the built-ins. Anyone who knowsmapalready knows how to usemyMap.
Higher-order functions are also useful outside of arrays. A common pattern wraps a callback with setup and cleanup that runs before and after it:
function measure(label, callback) {
const start = performance.now();
try {
return callback();
} finally {
const ms = (performance.now() - start).toFixed(2);
console.log(`${label} took ${ms} ms`);
}
}
const total = measure('sum', () => {
let s = 0;
for (let i = 0; i < 1e6; i++) s += i;
return s;
});
console.log(total); // 499999500000measure returns whatever the callback returns, and the finally block logs the timing even if the callback throws. That only works because the callback is synchronous. If the callback started a timer and returned, measure would report the time it took to start the work, not the time it took to finish.
Exercise
Predict the output of this code: console.log('start'); const r = [4, 5, 6].filter((x, i) => { console.log('check', x, i); return i !== 1; }); console.log(r); console.log('end');
Show answer
start, check 4 0, check 5 1, check 6 2, [4, 6], end. The filter callback runs synchronously for every element before filter returns, so all three "check" lines appear before the result is logged. The element at index 1 (the value 5) is dropped because the callback returns false for it.
Exercise
Write myEvery(array, predicate) that behaves like Array.prototype.every: it calls predicate(element, index, array), stops at the first falsy result, skips holes, and returns true for an empty array.
Show answer
function myEvery(array, predicate) { for (let i = 0; i < array.length; i++) { if (i in array && !predicate(array[i], i, array)) return false; } return true; } The early return false provides the short-circuit, the i in array check skips holes, and an empty array never enters the loop, so the function returns true.
Exercise
['10', '10', '10'].map(parseInt) returns [10, NaN, 2]. Explain each value and give a fix.
Show answer
map passes (element, index), so the calls are parseInt('10', 0), parseInt('10', 1), and parseInt('10', 2). A radix of 0 is treated as "not given", so the first call uses base 10 and returns 10. Radix 1 is invalid and gives NaN. Radix 2 reads '10' as binary, which is 2. The fix is to wrap the call so you control the arguments: .map((s) => parseInt(s, 10)), or use .map(Number).