Higher-Order Functions Explained With Examples
A higher-order function takes a function as an argument or returns one. Learn map, filter, reduce, and how to build your own abstractions.
By Velloreth
What makes a function higher-order
A higher-order function does at least one of two things:
- Takes a function as an argument.
- Returns a function.
That is the definition. It sounds abstract, but you already use higher-order functions constantly — every time you pass a callback to map, filter, setTimeout, or an event listener.
The significance is that functions become values. You can pass behaviour around, store it, return it, and compose it, exactly as you would pass a number or a string.
The three core functions
Almost every data transformation is a combination of map, filter, and reduce.
map: transform each element
const prices = [10, 20, 30];
const withTax = prices.map((p) => p * 1.13);
// [11.3, 22.6, 33.9]
map applies a function to every element and returns a new array of the same length. It never changes the original.
filter: keep what passes
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter((n) => n % 2 === 0);
// [2, 4, 6]
filter keeps the elements for which the predicate returns true. The result is the same length or shorter.
reduce: combine into one value
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 10
reduce walks the array carrying an accumulator. The second argument is the starting value, and the return value is whatever the accumulator ends up as — a number, a string, an object, or another array.
reduce is the most powerful of the three and the hardest to read. It can implement map and filter:
const doubled = numbers.reduce((acc, n) => [...acc, n * 2], []);
const evens = numbers.reduce((acc, n) => (n % 2 === 0 ? [...acc, n] : acc), []);
That it can does not mean it should. Prefer map and filter when they express the intent, and reach for reduce when you are genuinely combining into a single value.
Replacing loops with intent
The clearest argument for higher-order functions is readability. Compare:
// Loop
const result = [];
for (let i = 0; i < users.length; i++) {
if (users[i].active) {
result.push(users[i].name.toUpperCase());
}
}
// Higher-order
const result = users
.filter((u) => u.active)
.map((u) => u.name.toUpperCase());
The second version says what it does: take active users, uppercase their names. The first says how: initialise an array, loop with an index, check a condition, push.
The loop version has more places to make a mistake — the index bound, the increment, the push target. The higher-order version has none of those moving parts.
Returning functions
The second half of the definition is returning functions, which is where higher-order functions get genuinely powerful.
function multiplier(factor) {
return (n) => n * factor;
}
const double = multiplier(2);
const triple = multiplier(3);
double(5); // 10
triple(5); // 15
multiplier returns a function that closes over factor. Each returned function remembers its own factor, so you can create specialised functions from a general one.
This is partial application: fixing some arguments now and supplying the rest later.
Building validators
function minLength(min) {
return (value) => value.length >= min;
}
const isUsername = minLength(3);
const isPassword = minLength(12);
isUsername('ab'); // false
isPassword('short'); // false
Building middleware
function withLogging(handler) {
return async (req, res) => {
const start = Date.now();
await handler(req, res);
console.log(`${req.method} ${req.url} ${Date.now() - start}ms`);
};
}
const route = withLogging(async (req, res) => {
res.end('hello');
});
withLogging takes a handler and returns a new handler with logging wrapped around it. This is the decorator pattern expressed as a higher-order function, and it is how Express middleware, React higher-order components, and Python decorators all work.
Building pipelines
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const process = pipe(
(s) => s.trim(),
(s) => s.toLowerCase(),
(s) => s.replace(/\s+/g, '-'),
);
process(' Hello World '); // 'hello-world'
pipe takes any number of functions and returns one function that applies them in order. This is composition, and it is the foundation of functional data pipelines.
Common higher-order functions
| Function | Purpose |
|---|---|
map | Transform each element |
filter | Keep elements passing a test |
reduce | Combine into one value |
forEach | Run a side effect per element |
find | First element passing a test |
some | Does any element pass? |
every | Do all elements pass? |
sort | Order by a comparator |
flatMap | Map then flatten one level |
groupBy (proposal) | Group elements by a key |
some and every are worth highlighting because they short-circuit — they stop as soon as the answer is known, which a manual loop often fails to do.
Higher-order functions in other languages
Python has map, filter, and functools.reduce, plus comprehensions that often read better:
squares = [x * x for x in range(10)]
evens = [x for x in range(10) if x % 2 == 0]
Java uses streams:
List<String> names = users.stream()
.filter(User::isActive)
.map(User::getName)
.toList();
Rust uses iterators, which are lazy and zero-cost:
let sum: i32 = numbers.iter().filter(|n| **n % 2 == 0).sum();
Go is the outlier: it has no built-in map or filter, and the community convention is to write explicit loops. Generics added in Go 1.18 make libraries possible, but the standard library still favours loops.
The costs
Higher-order functions are not free.
Performance. Each call has overhead, and the engine may not inline as aggressively as it would a loop. For most code this is irrelevant; in a hot loop over millions of elements, it can matter.
Stack traces. An error inside a callback produces a stack trace with anonymous frames, which is harder to read than a named function.
Debugging. You cannot set a breakpoint on “the third iteration” as easily as with a loop.
Over-abstraction. Chaining five higher-order functions can be less readable than a single loop, especially when the logic is intricate.
The judgement is the same as everywhere: use them where they make the code clearer, and accept a loop where the loop is clearer.
Practical guidance
- Prefer
map/filter/reduceover manual loops for data transformation. - Name your callbacks when the logic is more than a line, for better stack traces.
- Avoid chaining more than three or four operations without extracting a named function.
- Use
some/everyinstead offilter().length— they short-circuit. - Do not mutate inside
map— that is whatforEachis for, and mixing the two confuses readers. - Remember that
sortmutates — usetoSortedor copy first.
For the related concepts, see closures explained and pure functions and side effects. For how these compose into larger designs, dependency injection without a framework and art of naming code.
Quotable summary
A higher-order function takes a function as an argument or returns one, which makes functions into values that can be passed, stored, and composed. map transforms each element, filter keeps elements passing a test, and reduce combines elements into a single value; most data transformations are combinations of these three. Returning functions enables partial application and closures, which is how validators, middleware, and pipelines are built. Higher-order functions replace repetitive loops with named intent, making code shorter and harder to get wrong. The costs are a small performance overhead, less readable stack traces, and the risk of over-abstraction when chains grow long.