Sub topic 7
Higher-Order Functions
A higher-order function is a function that takes another function as an argument, returns a function, or does both. Earlier chapters showed that JavaScript functions are values and that closures let a function keep its surrounding variables. Higher-order functions build on both ideas. They let you separate what should happen from when or how often it happens.
This chapter assumes you are comfortable with arrow functions, rest and spread syntax, closures, and the idea of first-class functions. The array methods map, filter, and reduce are higher-order functions too, but they get their own chapter next. Here the focus is the general pattern: how to recognize it, write your own, and avoid the mistakes people commonly make with it.
The Two Shapes of a Higher-Order Function
Every higher-order function has one or both of these shapes:
| Shape | What it does | Built-in examples |
|---|---|---|
| Takes a function | Calls your function at a time or in a way it controls | `setTimeout`, `addEventListener`, `Array.prototype.sort`, `Promise.prototype.then` |
| Returns a function | Builds and configures a new function for later use | `Function.prototype.bind`, factory functions you write |
| Both | Wraps a function to add behavior around it | `once`, `debounce`, logging and timing wrappers |
Taking a Function as an Argument
When a function accepts a callback, it owns the control flow and you supply the behavior. A loop is the simplest example:
function repeat(n, action) {
for (let i = 0; i < n; i++) {
action(i);
}
}
repeat(3, (i) => console.log(`step ${i}`));
// step 0
// step 1
// step 2
const squares = [];
repeat(4, (i) => squares.push(i * i));
console.log(squares); // [ 0, 1, 4, 9 ]repeat knows how to count. It does not know or care what happens on each step. The caller decides that. This split is what makes higher-order functions reusable. You write the control structure once and plug different behavior into it.
Returning a Function
A function that returns a function works like a factory. You give it configuration now, and it hands back a function that uses that configuration later. The returned function reads the configuration through a closure.
const greaterThan = (limit) => (n) => n > limit;
const isAdult = greaterThan(17);
const isLarge = greaterThan(1000);
console.log(isAdult(21)); // true
console.log(isAdult(12)); // false
console.log(isLarge(500)); // false
const prices = [12, 1500, 80, 2400];
console.log(prices.filter(isLarge)); // [ 1500, 2400 ]greaterThan never compares anything itself. It produces small, named predicates that you can pass to other higher-order functions. Factories like this let you name intent (isAdult) instead of repeating an inline lambda ((n) => n > 17) across a codebase.
Wrapping Functions: Taking and Returning
The most useful higher-order functions do both. They accept a function and return a new function with extra behavior around the original. The caller uses the wrapped version exactly as it would use the original.
`once`: Run a Function a Single Time
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")The called flag and the cached result live in the closure, so each call to once creates its own state. once also passes every argument through with rest and spread, which means it works for functions of any arity.
Preserving `this` in Wrappers
An arrow function has no this of its own. If you wrap an object method with an arrow-based wrapper, the method loses its receiver. When a wrapper might be used on methods, return a regular function and forward this with apply:
const withLogging = (fn, label = fn.name) =>
function (...args) {
console.log(`→ ${label}(${args.join(', ')})`);
const result = fn.apply(this, args);
console.log(`← ${label} returned ${result}`);
return result;
};
const account = {
balance: 100,
deposit(amount) {
this.balance += amount;
return this.balance;
}
};
account.deposit = withLogging(account.deposit, 'deposit');
account.deposit(25);
// → deposit(25)
// ← deposit returned 125When account.deposit(25) runs, this inside the returned function is account, and fn.apply(this, args) passes it on to the original method.
`debounce`: Controlling When a Function Runs
A wrapper can also change when a function runs. debounce delays a call until a burst of calls has stopped. It is common for search boxes and resize handlers.
const debounce = (fn, ms) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
};
const save = debounce((text) => console.log(`saved: ${text}`), 200);
save('h');
save('he');
save('hello'); // only this one runs, about 200 ms later: saved: helloThe calling code stays the same. The timing policy lives in one reusable place.
Common Errors
Calling the Function Instead of Passing It
const greet = () => console.log('hello');
// Wrong: greet() runs now and passes undefined to setTimeout
// setTimeout(greet(), 1000);
// Right: pass the function itself
setTimeout(greet, 1000);
// Right: wrap it when you need arguments
const greetName = (name) => console.log(`hello, ${name}`);
setTimeout(() => greetName('Ada'), 1000);greet is the function. greet() is its return value. A higher-order function needs the function.
Callback Arity Mismatch
Higher-order functions often pass more arguments than you expect. map calls its callback with (element, index, array), and parseInt takes (string, radix):
console.log(['10', '10', '10'].map(parseInt));
// [ 10, NaN, 2 ] index is used as the radix
const unary = (fn) => (x) => fn(x);
console.log(['10', '10', '10'].map(unary(parseInt)));
// [ 10, 10, 10 ]Passing a function by reference only works when its parameters match what the caller supplies. When they don't, wrap the function in a lambda or a helper such as unary that drops the extra arguments.
Losing `this` When Passing a Method
const counter = {
count: 0,
add(n) {
this.count += n;
}
};
// [1, 2, 3].forEach(counter.add); // TypeError in strict mode: this is undefined
[1, 2, 3].forEach(counter.add.bind(counter));
[1, 2, 3].forEach((n) => counter.add(n));
console.log(counter.count); // 12counter.add is a plain function value once you detach it from counter. Bind it, or call it through an arrow function that keeps the receiver.
Forgetting to Return from a Braced Arrow
const doubleBad = (fn) => (x) => { fn(x) * 2; }; // returns undefined
const doubleGood = (fn) => (x) => fn(x) * 2;
const inc = (x) => x + 1;
console.log(doubleBad(inc)(3)); // undefined
console.log(doubleGood(inc)(3)); // 8A braced arrow body needs an explicit return. This bug is easy to miss in nested returned functions.
When to Write One
A higher-order function is worth writing when:
- The same control structure (retry, timing, caching, guarding) appears around several different operations.
- You want to configure behavior once and reuse it under a meaningful name, as
greaterThandoes. - Cross-cutting concerns such as logging, timing, or access checks would otherwise clutter business logic.
Skip it when there is only one caller and a plain function reads more clearly. Each layer of wrapping adds an extra stack frame to debug, and anonymous returned functions show up as unnamed in stack traces. Give returned functions names, or assign them to named constants, when traces matter.
Exercise
Write a higher-order function negate(predicate) that returns a new predicate giving the opposite boolean result. Use it with greaterThan(10) to filter [5, 15, 8, 30] down to the values that are not greater than 10.
Show answer
const negate = (predicate) => (...args) => !predicate(...args); const greaterThan = (limit) => (n) => n > limit; console.log([5, 15, 8, 30].filter(negate(greaterThan(10)))); // [ 5, 8 ]. Forwarding ...args lets negate work with predicates of any arity.
Exercise
Why does ['1', '2', '3'].map(parseInt) return [1, NaN, NaN], and what are two ways to fix it?
Show answer
map calls the callback with (element, index, array), so parseInt receives the index as its radix: parseInt('1', 0) is 1 (radix 0 means default), parseInt('2', 1) is NaN (radix 1 is invalid), and parseInt('3', 2) is NaN ('3' is not a binary digit). Fix it with an explicit lambda, .map((s) => parseInt(s, 10)), or with a unary helper, .map(unary(parseInt)), or by using Number, which takes one argument.
Exercise
Write after(n, fn), which returns a function that does nothing on its first n - 1 calls and calls fn (returning its result) on the nth call and every call after that.
Show answer
const after = (n, fn) => { let calls = 0; return (...args) => { calls += 1; return calls >= n ? fn(...args) : undefined; }; }; const ready = after(3, () => 'go'); console.log(ready(), ready(), ready()); // undefined undefined go