Higher-Order Functions

Difficulty: Intermediate

Question

What is a higher-order function in JavaScript? Explain with practical examples, including how you would write one yourself.

Answer

A higher-order function (HOF) is a function that takes another function as an argument, returns a function, or both. JavaScript supports this because functions are first-class values: they can be stored in variables, passed around and returned like any other value. map, filter, reduce, setTimeout and addEventListener are all higher-order functions.

Two kinds of higher-order functions

Many useful HOFs do both: debounce(fn, 300) takes a function and returns a new, rate-limited one.

Why they matter

  1. Abstraction. You stop rewriting the same loop. Compare a for loop with an index, a temporary array and a push, against orders.filter(o => o.status === 'PAID').
  2. Composition. Small, single-purpose functions can be chained: orders.filter(isPaid).map(toAmount).reduce(sum, 0).
  3. Behaviour injection. You can wrap a function to add logging, retries, caching or authorization without touching its body. This is the decorator idea.
  4. Declarative code. Code describes what you want, which is easier to review and test.

Built-in higher-order functions to know

FunctionTakesReturns
map(fn)transform functionnew array of same length
filter(fn)predicatenew array of matching items
reduce(fn, init)reducer (acc, item)single accumulated value
find, some, everypredicateitem or boolean, stops early
sort(compareFn)comparatorthe same array, sorted in place
Function.prototype.bindthis and argsnew bound function

Since ES2023 there are non-mutating versions toSorted, toReversed and toSpliced, which pair better with functional code than the in-place sort.

Common mistakes

Functions passed into functions. Each method is a higher-order function: it takes your callback. Write your own callbacks under Tweak.
  1. Callback in: map receives x => x * x and calls it per element.
  2. Function as data: reduce receives (acc, x) => acc + x.
  3. Result: [1,2,3,4,5] squared and summed is 55.

Code examples

Functions as arguments: built-ins and your own map

const orders = [
  { id: 1, status: 'PAID', amountPaise: 49900 },
  { id: 2, status: 'FAILED', amountPaise: 19900 },
  { id: 3, status: 'PAID', amountPaise: 129900 },
];

const isPaid = (o) => o.status === 'PAID';
const toAmount = (o) => o.amountPaise;
const sum = (acc, n) => acc + n;

const revenue = orders.filter(isPaid).map(toAmount).reduce(sum, 0);
console.log(`Revenue: Rs ${revenue / 100}`);

// Writing your own higher-order function: a simplified map
function myMap(array, callback) {
  const result = [];
  for (let i = 0; i < array.length; i++) {
    result.push(callback(array[i], i, array));
  }
  return result;
}
console.log(myMap([1, 2, 3], (n) => n * 10));

// Gotcha: map passes (value, index), parseInt reads index as radix
console.log(['1', '2', '3'].map(parseInt));
console.log(['1', '2', '3'].map(Number));

filter, map and reduce each accept a callback, which is what makes them higher-order. Implementing myMap shows the callback contract (value, index, array), which also explains the parseInt surprise.

Functions that return functions

// Factory: the returned function remembers prefix via closure
function createLogger(prefix) {
  return (message) => console.log(`[${prefix}] ${message}`);
}
const payLog = createLogger('PAYMENTS');
payLog('UPI collect request sent');

// Decorator: wrap any function to add timing without editing it
function withTiming(fn) {
  return function (...args) {
    const start = performance.now();
    const result = fn.apply(this, args);
    console.log(`${fn.name} took ${(performance.now() - start).toFixed(2)}ms`);
    return result;
  };
}

const slowSquare = (n) => { for (let i = 0; i < 1e6; i++); return n * n; };
const timedSquare = withTiming(slowSquare);
console.log(timedSquare(12));

createLogger is a factory and withTiming is a decorator; both return new functions. The timing value will differ on your machine.

Key points

Common follow-up questions

Interview tips

Concepts covered

Higher-Order Functions, First-Class Functions, Callbacks, Function Factories, Closures

More JavaScript Interview questions