A higher-order function is a function that either takes another function as an argument, returns a function, or does both. It treats functions as values, enabling powerful patterns like callbacks, closures, and function composition.
What is the definition of a higher-order function?
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
The Core Idea
In JavaScript, a higher-order function is any function that either:
- Takes one or more functions as arguments, or
- Returns another function as its result.
In other words, it treats functions as values — passing them around just like variables.
Feature | Description | Example |
|---|---|---|
Accepts functions as arguments | A function receives another function and calls it inside. |
|
Returns a function | A function produces another function when called. |
|
Example 1: Taking a Function as an Argument
Functions like map, filter, and forEach are classic examples — they take another function and apply it to elements of an array.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]
Example 2: Returning a Function
A function can return another function that 'remembers' the outer scope — this is often used in currying or closures.
function greet(message) {
return function(name) {
console.log(`${message}, ${name}!`);
};
}
const sayHello = greet('Hello');
sayHello('Alice'); // Hello, Alice!
Why It Matters
Higher-order functions are the foundation of modern JavaScript patterns like:
- Callbacks (e.g., event handlers)
- Promises and async/await
- Functional utilities like
map,reduce,filter - Middleware and decorators in frameworks like Express or Redux.
Think of a higher-order function like a chef that doesn’t cook food directly — it takes other chefs (functions) and tells them how to cook. The chef can even create a new chef recipe on the spot and hand it back to you!
A higher-order function:
- Takes one or more functions as parameters or returns a function.
- Enables reusability and abstraction in code.
- Is a key building block of functional programming in JavaScript.