Higher-order function
A higher-order function is a function that takes another function as an argument or returns a function as its result.
Detailed explanation
In JavaScript, functions are first-class citizens, which means they can be:
- passed as values,
- stored in variables,
- returned from other functions.
Functions that use other functions this way are called higher-order.
Code examples
1. Takes a function as an argument
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 passed-in action function.
2. Returns 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.
3. Built-in examples in JS
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 functionWhy they are needed
They increase flexibility and code reuse. They let you implement abstractions, for example handling collections, events, and so on. They are the core tool of functional programming.
Summary
| 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 |
In one phrase:
A higher-order function is a function that treats other functions as data, taking them as arguments or returning them as a result.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.