Glossary / Higher-order functions

Higher-order functions

A higher-order function accepts a function as an argument, returns a function, or does both. This lets code represent behavior as data: a caller supplies the transformation, predicate, callback, or policy while the higher-order function handles iteration, registration, composition, or resource management. Array methods, event APIs, middleware, retry wrappers, and memoizers are common examples.

Common patterns

const names = users
  .filter((user) => user.active)
  .map((user) => user.name);

function withLogging(operation, logger) {
  return async (...args) => {
    logger.info("starting");
    try { return await operation(...args); }
    catch (error) { logger.error(error); throw error; }
  };
}

Higher-order functions can centralize policies such as retries, authorization, logging, or measurement. They may create closures and therefore retain captured objects; returned wrappers can change this, function names, stack traces, or error timing unless designed to preserve those contracts. Array callbacks receive (value, index, array), which is why passing a function such as parseInt directly can produce surprising output: the second argument may be interpreted as a radix.

Good abstractions and failure modes

Use a higher-order abstraction when it removes duplicated control flow and gives behavior a clear name. Avoid callback pyramids, hidden retry loops, callbacks invoked multiple times without documentation, and wrappers that swallow errors. Async higher-order functions must state whether they await each callback, run callbacks concurrently, or stop on first rejection.

Interview questions

  1. Why is map higher-order? It accepts a callback that defines how each element is transformed.
  2. What is a callback contract? Its invocation count/order, inputs, async semantics, receiver, errors, and cancellation behavior.
  3. Why can array.map(parseInt) be wrong? map passes the index as the second callback argument, which parseInt treats as radix.
  4. What can a wrapper accidentally change? this, errors, async timing, function identity, and metadata.

References