Skip to content
Velloreth
Programming 6 min read

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

What makes a function higher-order

A higher-order function does at least one of two things:

  1. Takes a function as an argument.
  2. 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

FunctionPurpose
mapTransform each element
filterKeep elements passing a test
reduceCombine into one value
forEachRun a side effect per element
findFirst element passing a test
someDoes any element pass?
everyDo all elements pass?
sortOrder by a comparator
flatMapMap 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/reduce over 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/every instead of filter().length — they short-circuit.
  • Do not mutate inside map — that is what forEach is for, and mixing the two confuses readers.
  • Remember that sort mutates — use toSorted or 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.

Frequently asked questions

What is a higher-order function in simple terms?
A higher-order function is a function that works with other functions, either by taking one as an argument or by returning one. Array.map is a higher-order function because you pass it a function that transforms each element.
What is the difference between map, filter, and reduce?
map transforms every element and returns an array of the same length. filter keeps only the elements that pass a test. reduce combines all elements into a single value, such as a sum or an object.
Why are higher-order functions useful?
They let you pass behaviour as a value, which removes repetitive loops and names the intent of the code. Instead of writing a loop that filters and transforms, you write filter then map, and the reader sees what is happening rather than how.
What is a callback function?
A callback is a function passed to another function to be called later. Every callback is an argument to a higher-order function, so callbacks and higher-order functions are two views of the same relationship.
What is the difference between a higher-order function and a closure?
A higher-order function takes or returns functions. A closure is a function that remembers variables from the scope where it was created. They often appear together, because a function returned from another function usually closes over the outer function's variables.
Are higher-order functions slower?
Slightly, because each call has overhead and the engine may not inline as aggressively. The difference is rarely significant, and modern engines optimise common cases well. Choose them for clarity unless profiling shows a problem.