What are Higher-Order Functions?

A higher-order function is a function that takes another function as an argument, returns a function, or both; it is possible because functions are values in JavaScript.

Built-in examples

map, filter, reduce, forEach, sort, find, some, every, setTimeout, addEventListener, Promise.then. They all take a function that defines the specific behaviour, while they handle the general part (looping, scheduling, waiting).

Functions that return functions

  • Function factories: makeMultiplier(2).
  • Decorators/wrappers that add behaviour to an existing function: debounce, throttle, memoize, once, logging, retry, timing.
  • Middleware: Express and Redux middleware are functions returning functions.
  • Currying and partial application.

Why they matter

  • Abstraction: separate what to do from how to iterate, wait or repeat.
  • Reuse: one retry wrapper works for any async function.
  • Composition: small functions combine into pipelines.
  • Declarative code: users.filter(isActive).map(toCard) reads like a description of the result.

In React

Hooks and render functions are built on the same idea. Higher-order components (withAuth(Component)) were the classic pattern before hooks; they still appear in older codebases.

Tip

Keep the functions you pass in small and named (isActive, byDate) so higher-order calls read like sentences.

Code example

js
1// Takes a function
2const isActive = (u) => u.active;
3const toLabel = (u) => `${u.name} (${u.role})`;
4const users = [
5 { name: "Ada", role: "admin", active: true },
6 { name: "Linus", role: "user", active: false },
7];
8console.log(users.filter(isActive).map(toLabel)); // ["Ada (admin)"]
9
10// Returns a function: a reusable wrapper that adds behaviour
11function withLogging(fn) {
12 return (...args) => {
13 const result = fn(...args);
14 console.log(`${fn.name}(${args.join(", ")}) = ${result}`);
15 return result;
16 };
17}
18const add = (a, b) => a + b;
19withLogging(add)(2, 3); // add(2, 3) = 5
20
21// Retry wrapper for any async function
22function withRetry(fn, attempts = 3) {
23 return async (...args) => {
24 for (let i = 1; ; i++) {
25 try {
26 return await fn(...args);
27 } catch (e) {
28 if (i >= attempts) throw e;
29 }
30 }
31 };
32}
33let calls = 0;
34const flaky = async () => (++calls < 3 ? Promise.reject(new Error("flaky")) : "ok on attempt " + calls);
35console.log(await withRetry(flaky)()); // ok on attempt 3
36
37// Function factory
38const makeMultiplier = (factor) => (n) => n * factor;
39console.log([1, 2, 3].map(makeMultiplier(10))); // [10, 20, 30]

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app