# Higher-Order Functions

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

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-higher-order-functions
Last updated: 2026-11-28

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

- **Functions that accept functions.** The caller supplies the "what" and the HOF supplies the "how". `array.filter(isAvailable)` owns the looping; you only describe the rule. The function you pass in is called a callback.
- **Functions that return functions.** These are function factories. `createLogger('PAYMENTS')` returns a logger that remembers its prefix through a closure. Middleware, debounce, memoize and React's `connect` style APIs all follow this shape.

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

| Function | Takes | Returns |
| --- | --- | --- |
| `map(fn)` | transform function | new array of same length |
| `filter(fn)` | predicate | new array of matching items |
| `reduce(fn, init)` | reducer `(acc, item)` | single accumulated value |
| `find`, `some`, `every` | predicate | item or boolean, stops early |
| `sort(compareFn)` | comparator | the same array, sorted in place |
| `Function.prototype.bind` | `this` and args | new 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

- Passing a function that relies on extra parameters, like `['1','2','3'].map(parseInt)`, which returns `[1, NaN, NaN]` because `map` passes `(value, index)` and `parseInt` treats the index as a radix.
- Calling the function instead of passing it: `setTimeout(doWork(), 1000)` runs immediately.
- Losing `this` when passing methods: `button.addEventListener('click', obj.handle)` calls `handle` with `this` set to the button. Use an arrow wrapper or `bind`.
- Chaining `map().filter()` over huge arrays in a hot path creates intermediate arrays; a single `reduce` or a plain loop can be cheaper when it actually matters.

**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

- A higher-order function takes a function, returns a function, or both.
- This works because JavaScript functions are first-class values.
- Functions returning functions rely on closures to remember configuration.
- map, filter, reduce, find, some, every, sort, bind, setTimeout and addEventListener are all HOFs.
- Watch for extra callback arguments (map passes index) and lost this when passing methods.

## Common follow-up questions

- Implement Array.prototype.reduce from scratch.
- What is the difference between a callback and a higher-order function?
- How do closures relate to function factories?
- What is function composition and how would you write pipe()?
- Why does \['1','2','3'\].map(parseInt) return \[1, NaN, NaN\]?

## Interview tips

- Give both directions (takes a function, returns a function) with one example each.
- Writing a polyfill for map or filter on the spot is a common follow-up, so practise it.
- Mention a real use such as debounce or middleware to show you use HOFs beyond array methods.

## Concepts covered

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

Previous: [Event Bubbling, Capturing & Event Flow](https://www.internhack.in/learn/interview/javascript-interview/js-event-bubbling) · Next: [Callback Hell & Async Patterns](https://www.internhack.in/learn/interview/javascript-interview/js-callback-patterns) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Symbols & Well-Known Symbols](https://www.internhack.in/learn/interview/javascript-interview/js-symbols)
- [Proxy and Reflect API](https://www.internhack.in/learn/interview/javascript-interview/js-proxy-reflect)
- [WeakMap and WeakSet](https://www.internhack.in/learn/interview/javascript-interview/js-weakmap-weakset)
- [Generator Functions](https://www.internhack.in/learn/interview/javascript-interview/js-generators)
- [Optional Chaining and Nullish Coalescing](https://www.internhack.in/learn/interview/javascript-interview/js-optional-chaining-nullish)
- [Currying and Function Composition](https://www.internhack.in/learn/interview/javascript-interview/js-currying-composition)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
