Higher-order function
A higher-order function is a function that takes another function as an argument or returns a function as its result. Either one of those two properties is enough for a function to count as higher-order.
Theory
TL;DR
- A higher-order function takes a function as an argument or returns a function.
- This works because functions in JavaScript are first-class objects.
- A function can be passed as a value, stored in a variable and returned from another function.
- Built-in examples:
map,filter,reduce,setTimeout,addEventListener. - They give flexibility, logic reuse and abstractions over collections and events.
- They are the main tool of functional programming.
Quick example
function repeat(n, action) {
for (let i = 0; i < n; i++) {
action(i);
}
}
repeat(3, console.log);
// 0
// 1
// 2repeat is a higher-order function because it calls the function action that was passed in.
Functions as first-class objects
In JavaScript functions are first-class citizens, which means you can:
- pass them around as values,
- store them in variables,
- return them from other functions.
Functions that use other functions in that way are exactly what we call higher-order functions.
const greet = function (name) { // store it in a variable
return `Hello, ${name}`;
};
const actions = [greet]; // put it in an array
console.log(actions[0]('Maria')); // Hello, MariaTaking a function as an argument
function repeat(n, action) {
for (let i = 0; i < n; i++) {
action(i);
}
}
repeat(3, console.log);
// 0
// 1
// 2The function passed in is usually called a callback. repeat itself knows nothing about what action will do: it is only responsible for the repetition. That separation of responsibilities is exactly what makes the code flexible.
Returning a new function
function multiplier(factor) {
return function (num) {
return num * factor;
};
}
const double = multiplier(2);
console.log(double(5)); // 10multiplier is a higher-order function because it returns another function. The returned function remembers factor thanks to the closure, so double always multiplies by 2, while multiplier(10) produces an independent function that multiplies by 10.
Built-in examples in JavaScript
Many array methods are higher-order functions:
[1, 2, 3].map(x => x * 2); // takes a function
[1, 2, 3].filter(x => x > 1); // takes a function
[1, 2, 3].reduce((a, b) => a + b, 0); // takes a functionThe same is true of browser and platform APIs: setTimeout(fn, 0), addEventListener('click', fn), promise.then(fn), arr.sort(compareFn). All of them accept a function and decide when and with which arguments to call it.
What they are for
- They increase the flexibility and reusability of code: one generic function serves many scenarios.
- They let you build abstractions, for example over collections, events or retries.
- They are the main tool of functional programming.
| Property | Description |
|---|---|
| What it does | Takes or returns functions |
| Examples | map, filter, reduce, setTimeout, addEventListener |
| Benefits | Logic reuse, more compact code |
| Key idea | Functions are data just like numbers or strings |
A higher-order function is a function that treats other functions as data: it takes them as arguments or returns them as a result.
Common mistakes
- Calling the function instead of passing it.
setTimeout(sayHi(), 1000)passes the result of the call, not the function itself; the correct form issetTimeout(sayHi, 1000). - Passing a method and losing
this.element.addEventListener('click', obj.handle)loses the context; you needobj.handle.bind(obj)or an arrow wrapper. - Confusing a callback with a higher-order function. The higher-order one is the function that accepts the callback, not the callback itself.
- Passing
parseIntstraight intomap.['1','2','3'].map(parseInt)gives[1, NaN, NaN], becausemapalso passes the index, which becomes the radix. - Thinking any function with an object argument is already higher-order. The value has to be a function, not ordinary data.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.