Higher-Order Functions

A function that takes another function as input, returns one as output, or both.

What is it?

Functions are values: you can store them in variables, put them in arrays and pass them around like numbers or strings. A higher-order function uses this: it takes a function as a parameter, returns a function, or both.

You've met several already. .map(), .filter() and .reduce() are higher-order because each takes a callback.

Explain like I'm 10

A higher-order function is like a manager who doesn't do the task directly. They take your instructions (a function) and apply them, or hand you back custom instructions (a function) built for a specific situation.

Examples

A function that returns a function

function multiplyBy(factor) {
  return function (n) {
    return n * factor;
  };
}

const double = multiplyBy(2);
const triple = multiplyBy(3);

console.log(double(5)); // 10
console.log(triple(5)); // 15

A function that takes a function as a parameter

function applyTwice(fn, value) {
  return fn(fn(value));
}

const addOne = (n) => n + 1;

console.log(applyTwice(addOne, 5)); // 7 — addOne(addOne(5))

applyTwice doesn't care what fn does; it applies whatever function it gets, twice. That flexibility is the point of taking a function as a parameter.

How it works

Functions are ordinary values, so returning one works like returning a number or string. The returned function is callable, and (thanks to closures) it remembers the variables from where it was created, like factor above.

Why does it exist?

Higher-order functions let you write general logic once (like "multiply by some factor") and customize it on demand, instead of writing a nearly identical function for every case.

When to use it

Use one to generate specialized functions from a general pattern (like multiplyBy), or when designing an API where the caller supplies custom behavior (like .map() accepting any transformation).

When not to use it

If a plain function with a couple of parameters does the job just as clearly, an extra layer of functions returning functions only adds indirection.

Common mistakes

  • Confusing a higher-order function with a callback — a higher-order function is the one accepting/returning functions; a callback is the function being passed in.

  • Forgetting to actually call the returned function — const double = multiplyBy(2) gives you a function, not a number.

  • Overusing function factories for cases that don't actually need customization.

Practice exercises

  1. Easy:

    Write a higher-order function add(a) that returns a function which adds a to whatever number it's given.

  2. Medium:

    Write a function compose(f, g) that returns a new function applying g then f to its input.

  3. Hard:

    Write a function debounce(fn, delay) that returns a version of fn which only runs after it hasn't been called for delay milliseconds.

Interview questions

What makes a function 'higher-order'?

It takes a function as an argument, returns a function, or both, treating functions like any other value.

What's the difference between a higher-order function and a callback?

They're two sides of one relationship. The higher-order function accepts or returns a function; the callback is the function passed in. In arr.map(fn), map is higher-order and fn is the callback.

Besides array methods, what are some built-in higher-order functions?

setTimeout/setInterval (take a function to run later), addEventListener (takes a handler) and promise methods like .then() (take functions to run on resolve/reject). Each takes a function as an argument.

What does this log? `function greaterThan(n) { return (m) => m > n; } const greaterThan10 = greaterThan(10); console.log(greaterThan10(15)); console.log([5, 12, 8, 20].filter(greaterThan10));`

true then [12, 20]. greaterThan(10) returns a function that closes over n = 10, used both on its own and as a filter callback.

What is function composition, and what does `compose(f, g)` typically mean?

Combining functions so one's output feeds the next one's input. compose(f, g) usually means "apply g, then f" (right to left), while pipe(f, g) usually runs left to right.

What does this log? `const compose = (f, g) => (x) => f(g(x)); const double = (n) => n * 2; const increment = (n) => n + 1; const doubleThenIncrement = compose(increment, double); console.log(doubleThenIncrement(3));`

7. compose(increment, double) applies double first (3 * 2 = 6), then increment (6 + 1 = 7). compose runs right to left, which matches the name doubleThenIncrement.

What is currying, and how is it different from ordinary partial application?

Currying turns a multi-argument function into a chain of functions that each take exactly one argument. Partial application is more general: fix some arguments now and return a function that takes the rest, one at a time or several at once.

What does this log? `const add = (a) => (b) => (c) => a + b + c; console.log(add(1)(2)(3));`

6. Each call returns the next function in the chain, closing over the argument just given, so the last call has all three to add.

Why do higher-order functions that return other functions rely on closures to be useful?

The returned function usually needs to remember something from the call that created it, like a multiplier or a cache. Without a closure, it couldn't reach those values once the outer call ended.

What is a decorator/wrapper pattern implemented as a higher-order function?

A function that takes a function and returns a new one with extra behavior around it. For example, withLogging(fn) returns a function that logs the arguments and then calls fn(...args), keeping the original behavior but adding logging.

How does memoization work as a higher-order function?

memoize(fn) returns a function that checks a closed-over cache for the arguments before calling fn. On a hit it returns the cached result; otherwise it runs fn, stores the result and returns it.

Why are higher-order functions considered a core building block of functional programming?

Functional programming treats functions as first-class values to compose, pass around and generate. Higher-order functions are the mechanism for combining small, reusable functions into bigger behavior.

What's the practical difference between `return fn;` and `return fn();` inside a higher-order function?

return fn; returns the function itself, to be called later. return fn(); calls it now and returns its result. Mixing them up causes "why is this a function instead of a value" bugs (or the reverse).

How would you build a `debounce(fn, delay)` higher-order function?

Return a function that, on every call, clears the previous timer (kept in a closed-over variable) and starts a new setTimeout to call fn after delay. So fn runs only once calls have stopped for that long.

What does it mean for JavaScript to have 'first-class functions', and why does that matter for higher-order functions?

Functions can be stored in variables and data structures, passed as arguments and returned, like any value. Without that, higher-order functions couldn't exist.

How would you implement a `once(fn)` higher-order function that only lets `fn` run a single time?

Close over a flag (and optionally a cached result) in the returned function. The first call runs fn, stores the result and flips the flag; later calls skip fn and return the stored result.

Is a callback ever itself a higher-order function?

Yes, when the callback itself takes or returns a function, for example passing memoize or compose as an argument. Being a callback and being higher-order are independent. Note that the function returned by greaterThan(10) is not higher-order: (m) => m > n takes a number and returns a boolean. greaterThan is the higher-order one.