Sub topic 7
Higher-Order Functions
This chapter assumes you know arrow functions, rest and spread syntax (...args), and closures from the earlier chapter. A higher-order function is a function that takes a function as an argument, returns a function, or does both. Since JavaScript treats functions as values, you can pass them around like numbers or strings. Higher-order functions are how you package up behavior so you can reuse it.
Taking a function as an argument
When a function accepts another function, the caller supplies the part that changes and the higher-order function supplies the part that stays the same.
const repeat = (n, action) => {
for (let i = 0; i < n; i++) action(i);
};
repeat(3, (i) => console.log(`step ${i}`));
// step 0
// step 1
// step 2repeat handles the looping, and the callback decides what happens on each pass. You already use this pattern with setTimeout, addEventListener, and Array.prototype.sort.
Returning a function
A higher-order function can also build a new function and return it. The returned function is a closure, so it keeps access to the arguments it was created with. This lets you add behavior to an existing function without editing it.
const withLogging = (fn) => (...args) => {
const result = fn(...args);
console.log(`${fn.name}(${args.join(', ')}) -> ${result}`);
return result;
};
const add = (a, b) => a + b;
const loggedAdd = withLogging(add);
loggedAdd(2, 3); // logs: add(2, 3) -> 5Here is a wrapper that keeps state, which is common in real code. It makes sure a function runs only once:
const once = (fn) => {
let called = false;
let result;
return (...args) => {
if (!called) {
called = true;
result = fn(...args);
}
return result;
};
};
const init = once(() => {
console.log('initializing');
return 42;
});
console.log(init()); // initializing, then 42
console.log(init()); // 42 (no second "initializing")Common patterns
| Pattern | Takes a function | Returns a function | Example |
|---|---|---|---|
| Callback | Yes | No | `repeat`, `setTimeout` |
| Factory | No | Yes | `makeCounter` |
| Decorator (wrapper) | Yes | Yes | `withLogging`, `once` |
Common errors
Calling instead of passing
setTimeout(save(), 1000) runs save right away and passes its return value to setTimeout. You should pass the function itself: setTimeout(save, 1000).
Extra arguments you didn't expect
Callbacks often get more arguments than you planned for. map passes (value, index, array), and parseInt reads its second argument as the radix:
console.log(['1', '2', '3'].map(parseInt)); // [ 1, NaN, NaN ]
console.log(['1', '2', '3'].map((s) => parseInt(s, 10))); // [ 1, 2, 3 ]Losing `this`
Exercise
Write a higher-order function unary(fn) that returns a function which calls fn with only its first argument. Use it to fix ['1', '2', '3'].map(parseInt).
Show answer
const unary = (fn) => (x) => fn(x); Then ['1', '2', '3'].map(unary(parseInt)) returns [1, 2, 3]. The wrapper drops the index that map passes, so parseInt falls back to its default parsing, which reads these strings as base 10.
Exercise
What does const f = once(Math.random); console.log(f() === f()); print, and why?
Show answer
It prints true. The first call stores the random number in the closure's result variable. Every later call skips fn and returns that same stored value.