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 run a script in Node.js or the browser console. It also builds on the previous chapters: functions are values, and a callback is a function you pass to another function so that function can call it.
What "synchronous" means for a callback
A higher-order function is a function that takes a function as an argument, returns one, or both. When a higher-order function calls its callback before it returns, the callback is synchronous. The caller's next line does not run until every callback invocation has finished.
That is the whole working model: synchronous callbacks run inline, in order, on the current call stack. Nothing is deferred and nothing is queued.
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 and Array.prototype.map behave the same way. Each one loops, calls the callback, and returns only after the loop ends. That is why doubled already holds the full result on the next line.
The built-in array methods
Each array method defines a contract for its callback: which arguments it passes and what it does with the return value.
| Method | Callback receives | Uses the return value as | Returns |
|---|---|---|---|
| `forEach` | `(element, index, array)` | Ignored | `undefined` |
| `map` | `(element, index, array)` | The new element | A new array of the same length |
| `filter` | `(element, index, array)` | Keep or drop (truthy or falsy) | A new array with the kept elements |
| `reduce` | `(accumulator, element, index, array)` | The next accumulator | The final accumulator |
| `find` | `(element, index, array)` | Stop when truthy | The first match or `undefined` |
const orders = [
{ id: 1, total: 40, paid: true },
{ id: 2, total: 15, paid: false },
{ id: 3, total: 90, paid: true },
];
const paidTotals = orders
.filter((order) => order.paid)
.map((order) => order.total);
const revenue = paidTotals.reduce((sum, total) => sum + total, 0);
orders.forEach((order, index) => {
console.log(index, order.id, order.paid ? 'paid' : 'open');
});
console.log(paidTotals); // [40, 90]
console.log(revenue); // 130Writing your own higher-order function
Your own higher-order function should follow the same contract style: document what it passes to the callback and what it expects back. Here is a minimal myFilter:
function myFilter(array, predicate) {
const result = [];
for (let i = 0; i < array.length; i++) {
if (predicate(array[i], i, array)) {
result.push(array[i]);
}
}
return result;
}
console.log(myFilter([5, 12, 8, 20], (n) => n > 10)); // [12, 20]Common errors
Forgetting to return
A map or filter callback with a block body { } needs an explicit return. Without one, the callback returns undefined.
const wrong = [1, 2, 3].map((x) => { x * 2; });
console.log(wrong); // [undefined, undefined, undefined]
const right = [1, 2, 3].map((x) => { return x * 2; });
console.log(right); // [2, 4, 6]Expecting forEach to return something or stop early
forEach always returns undefined, and return inside its callback only ends that one invocation. To stop early, use for...of with break, or use find or some.
Passing a function that takes extra parameters
Array methods pass three arguments, and some functions accept more than one parameter:
console.log(['10', '10', '10'].map(parseInt)); // [10, NaN, 2]
console.log(['10', '10', '10'].map((s) => parseInt(s, 10))); // [10, 10, 10]parseInt reads the index as its radix argument. Wrapping the call in an arrow function controls exactly which arguments get passed.
Exceptions propagate to the caller
A synchronous callback runs on the caller's stack, so an error it throws passes up through the higher-order function and can be caught by an ordinary try/catch around the call. Asynchronous callbacks, covered in the next chapter, do not work this way.
try {
[1, 2, 3].forEach((n) => {
if (n === 2) throw new Error('bad value ' + n);
});
} catch (err) {
console.log('Caught:', err.message); // Caught: bad value 2
}Exercise
Write a function times(n, callback) that calls callback(i) for i from 0 to n - 1 and returns an array of the callback's return values. What does times(3, (i) => i * i) return, and is the callback synchronous?
Show answer
function times(n, callback) { const out = []; for (let i = 0; i < n; i++) { out.push(callback(i)); } return out; } — it returns [0, 1, 4]. The callback is synchronous: every invocation finishes before times returns.
Exercise
What does this log, and why? const r = [1, 2, 3].forEach((x) => x * 2); console.log(r);
Show answer
It logs undefined. forEach ignores the callback's return values and always returns undefined. Use map to collect the doubled values.