Higher-Order Functions
A function that takes another function in, gives one back out, or both.
Loading visual…
Definition
A higher-order function is a function that does at least one of two things: it accepts one or more functions as arguments, or it returns a function as its result. This is possible because functions in JavaScript are first-class values, they can be stored in a variable, passed around like any other argument, and returned from another function, so nothing special has to happen for a function to end up as data flowing through your program. When a function is passed in as an argument, it is usually called a callback, and the outer function decides when to call it back, sometimes once, sometimes many times, sometimes not at all. `Array.prototype.map`, `filter`, and `reduce` are the most common higher-order functions you will use day to day: each one takes a function describing what to do with an element and calls it back for every item in the array. A higher-order function can also build and return a brand new function, which is how function factories work, a call like `multiplyBy(3)` does not multiply anything itself, it hands back a new function that will multiply by 3 whenever it is eventually called.
Examples
const numbers = [1, 2, 3, 4];
const doubled = numbers.map((n) => n * 2);
// [2, 4, 6, 8]map is a higher-order function: it takes the arrow function in as an argument and calls it back once per element.
function withLogging(fn) {
return (...args) => {
console.log("calling with", args);
return fn(...args);
};
}
const loggedAdd = withLogging((a, b) => a + b);
loggedAdd(2, 3); // logs, then returns 5withLogging both takes a function in and returns a new function out, wrapping the original with extra behavior without changing its code.
function multiplyBy(factor) {
return (n) => n * factor;
}
const triple = multiplyBy(3);
triple(5); // 15multiplyBy returns a function instead of a number. Calling triple later runs that returned function with the factor already locked in.
Where you see this
- Array methods like map, filter, and reduce, which take a function describing what to do with each element.
- Wrapping a function with extra behavior, such as logging, timing, or memoizing, without editing its original code.
- Middleware in web frameworks, where each layer receives the next handler as a function and decides whether to call it.
- Function factories that produce a family of related functions, like validators or formatters, from one shared setup.
- Registering event listeners, since addEventListener itself is a higher-order function that calls your handler back.