I. What Is a Higher-Order Function
A higher-order function (HOF) is a function that satisfies at least one of the following conditions:
- It accepts a function as an argument: another function is passed into the current function, and the current function decides when and how to call it.
- It returns a function as its result: the function returns another function when executed, allowing behavior to be deferred, composed, or dynamically generated.
As long as one of these conditions is met, it counts as a higher-order function.
1.1 Ordinary Functions vs. Higher-Order Functions
Ordinary functions typically take in data and return data:
function add(a, b) {
return a + b;
}
const result = add(10, 20);
A higher-order function can accept another function:
function calculate(a, b, operation) {
return operation(a, b);
}
const result = calculate(10, 20, add);
It can also return a function:
function createMultiplier(factor) {
return function (value) {
return value * factor;
};
}
const double = createMultiplier(2);
console.log(double(10)); // 20
1.2 Criteria for Identifying Higher-Order Functions
| Condition | Is It a Higher-Order Function? | Example |
|---|---|---|
| Takes ordinary numeric arguments | No | add(1, 2) |
| Takes a function argument | Yes | map(array, callback) |
| Returns an ordinary numeric value | No | getValue() |
| Returns a function | Yes | createHandler() |
| Takes a function and returns a function | Yes | Decorators, higher-order wrapper functions |
A few things to note:
- Passing a function as an argument does not in itself mean the caller will necessarily execute it immediately.
- Returning a function is not the same as immediately executing the returned function.
- Higher-order function describes a relationship between functions, not any particular syntax.
II. The Underlying Foundation of Higher-Order Functions
Higher-order functions are possible only because programming languages provide an important form of support for functions: functions can be manipulated and passed around like ordinary data.
This is usually closely tied to first-class functions.
2.1 First-Class Functions
First-class functions means that functions in a language have usage capabilities comparable to other ordinary values, typically including:
- They can be assigned to variables.
- They can be passed as arguments.
- They can be used as function return values.
- They can be stored in data structures such as arrays and objects.
- They can be created and called at runtime.
For example:
function greet(name) {
return `Hello, ${name}`;
}
// Assign to a variable
const fn = greet;
// Pass as an argument
function execute(callback) {
return callback("Reverie");
}
console.log(execute(fn));
// Store in an array
const handlers = [greet, fn];
// Retrieve from the array and call
console.log(handlers[0]("Developer"));
Here, greet, fn, and handlers[0] all point to callable function values.
2.2 The Difference Between First-Class Functions and Higher-Order Functions
These are not the same concept.
| Concept | Core Meaning | Focus |
|---|---|---|
| First-class function | Functions can be used as ordinary values | Language capability |
| Higher-order function | A function accepts or returns other functions | Function behavior |
| Anonymous function | A function without an explicit name | Form of function definition |
| Lambda expression | A function defined using a particular syntax | Expressive power of syntax |
| Closure | A function combined with the lexical environment it captures | Variable access and lifetime |
First-class functions provide the foundation for higher-order functions, but the two should not be conflated.
For example, just because a language supports assigning functions to variables does not mean all of its functions must be written as higher-order functions.
2.3 How Functions Are Executed as Values
When a function is passed as an argument, what is typically passed is the function value or a reference to the function, not the result of executing it.
function sayHello() {
console.log("Hello");
}
function execute(callback) {
callback();
}
// Pass the function itself
execute(sayHello);
// Pass the function's execution result
execute(sayHello());
These two forms are fundamentally different:
execute(sayHello): pass the function toexecute, which calls it internally.execute(sayHello()): first executesayHello(), then pass the execution result intoexecute.
If sayHello() does not return a function, the second form will usually result in the argument not being a callable function.
3. Two Basic Forms of Higher-Order Functions
Higher-order functions mainly have two forms: receiving a function as a parameter, and returning a function.
3.1 Receiving a Function as a Parameter
This is the most common form of higher-order functions.
function processData(data, callback) {
const result = data * 2;
return callback(result);
}
function format(value) {
return `结果:${value}`;
}
const result = processData(10, format);
console.log(result); // Result: 20
Execution process:
flowchart TD
A["Call processData"] --> B["Pass in data"]
B --> C["Pass in function callback"]
C --> D["Calculate intermediate result"]
D --> E["Call callback"]
E --> F["Return final result"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
The higher-order function is responsible for controlling the overall flow, while the passed-in function is responsible for providing the specific behavior.
This design separates:
- flow control from business logic.
- general processing logic from specific operations.
- fixed algorithm structure from variable behavior.
3.2 Returning a Function
A higher-order function can also return another function after execution.
function createAdder(base) {
return function (value) {
return base + value;
};
}
const add10 = createAdder(10);
const add20 = createAdder(20);
console.log(add10(5)); // 15
console.log(add20(5)); // 25
The function returned by createAdder can still access the base variable in the outer function.
Even after createAdder has finished executing, the returned function can still access the variable it captured.
This is a typical scenario where higher-order functions are combined with closures.
Execution process:
flowchart TD
A["Call createAdder(10)"] --> B["Create outer execution context"]
B --> C["Generate inner function"]
C --> D["Inner function captures base"]
D --> E["Return inner function"]
E --> F["Outer function finishes execution"]
F --> G["Call the returned function"]
G --> H["Read the captured base"]
H --> I["Compute and return the result"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
3.3 Combining the Two Forms
A higher-order function can both accept function parameters and return a function.
function compose(f, g) {
return function (value) {
return f(g(value));
};
}
function double(value) {
return value * 2;
}
function increment(value) {
return value + 1;
}
const composed = compose(double, increment);
console.log(composed(5)); // 12
Its execution logic:
composed(5)
→ increment(5)
→ 6
→ double(6)
→ 12
compose combines two functions into a new function, forming a reusable unit of behavior.
IV. Common Higher-Order Functions
Higher-order functions are very common in modern programming languages, especially in collection processing, asynchronous programming, event handling, and functional programming.
4.1 map: Mapping Transformation
map executes the specified function on each element in a collection and returns a new collection.
const numbers = [1, 2, 3, 4];
const result = numbers.map(function (item) {
return item * 2;
});
console.log(result); // [2, 4, 6, 8]
Processing logic:
flowchart TD
A["Input array"] --> B["Read current element"]
B --> C["Call mapping function"]
C --> D["Generate transformed result"]
D --> E{"Are there more elements?"}
E -->|"Yes"| B
E -->|"No"| F["Return new array"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Use cases:
- Data format conversion.
- Object property extraction.
- Data structure mapping.
- Consistent formatting.
4.2 filter: Conditional Filtering
filter filters elements based on the passed predicate function and returns a new collection of elements that meet the condition.
const numbers = [1, 2, 3, 4, 5, 6];
const result = numbers.filter(function (item) {
return item % 2 === 0;
});
console.log(result); // [2, 4, 6]
Elements for which the predicate function returns a truthy value are retained.
Use cases:
- Query data that meets the conditions.
- Filter out invalid records.
- Permission and status filtering.
- Data cleaning.
4.3 reduce: Reduction Computation
reduce progressively reduces multiple elements in a collection into a single result.
const numbers = [1, 2, 3, 4];
const total = numbers.reduce(function (acc, current) {
return acc + current;
}, 0);
console.log(total); // 10
Where:
acc: the accumulator, which holds the result of the previous computation.current: the element currently being processed.0: the initial accumulator value.
The reduction process:
flowchart TD
A["Initial value acc = 0"] --> B["Read element 1"]
B --> C["acc = 0 + 1"]
C --> D["acc = 1"]
D --> E["Read element 2"]
E --> F["acc = 1 + 2"]
F --> G["acc = 3"]
G --> H["Continue processing the remaining elements"]
H --> I["Final acc = 10"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
reduce is not limited to summing; it can also be used for:
- Grouped counting.
- Building objects.
- Data aggregation.
- Flattening multi-level structures.
- Accumulating state.
4.4 sort: Custom Sorting
sort can accept a comparator function, which defines the ordering rule between elements.
const numbers = [10, 3, 25, 7];
numbers.sort(function (a, b) {
return a - b;
});
console.log(numbers); // [3, 7, 10, 25]
In JavaScript:
- The comparator returns a negative number:
acomes beforeb. - It returns a positive number:
bcomes beforea. - It returns zero: the two are considered equal under the sorting rule.
Note that JavaScript's sort modifies the original array in place. If you need to preserve the original array, you can copy it first and then sort:
const sorted = [...numbers].sort((a, b) => a - b);
4.5 forEach: Iterating and Executing
forEach accepts a callback function and performs the specified operation on each element in the collection.
const names = ["Alice", "Bob", "Tom"];
names.forEach(function (name) {
console.log(name);
});
Its main differences from map:
| Aspect | map | forEach |
|---|---|---|
| Accepts a callback | Yes | Yes |
| Returns a new array | Yes | No, returns undefined |
| Primary use | Data transformation | Iterating to perform side effects |
| Suitable for chained data processing | Yes | Usually not |
V. Higher-Order Functions and Callback Functions
Higher-order functions and callback functions often appear together, but the two represent different roles.
5.1 What Is a Callback Function
A callback function is a function that is passed as an argument to another function and is invoked by the receiving function at the appropriate time.
function fetchData(callback) {
const data = {
id: 1,
name: "Reverie"
};
callback(data);
}
function handleData(data) {
console.log(data.name);
}
fetchData(handleData);
In this example:
fetchDatais a higher-order function.handleDatais a callback function.callbackis the parameter that receives the callback function.
5.2 Relationship Between the Two
| Concept | Role | Description |
|---|---|---|
| Higher-order function | Receiver or returner | Receives a function or returns a function |
| Callback function | The function being passed | Called by the receiver at the appropriate time |
| Function parameter | Passing carrier | Used to receive a function value |
A callback function is not necessarily an asynchronous function.
For example:
[1, 2, 3].map(item => item * 2);
The callback function in map is executed synchronously.
In contrast, the following callback function is executed by a timer in a later event loop:
setTimeout(() => {
console.log("执行完成");
}, 1000);
Therefore, a callback describes the passing and calling relationship of functions, while asynchrony describes execution timing; the two must not be conflated.
6. The Relationship Between Higher-Order Functions and Closures
Higher-order functions and closures are often used together, but they solve different problems.
- Higher-order functions: control the passing, composition, and return of functions.
- Closures: enable a function to access the lexical environment in which it was defined.
For example:
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
Two concepts are involved here at the same time:
createCounterreturns a function, so it is a higher-order function.- The returned function can continue to access
count, so it forms a closure.
Closures allow functions to hold independent state.
Multiple calls can have different states:
const counterA = createCounter();
const counterB = createCounter();
console.log(counterA()); // 1
console.log(counterA()); // 2
console.log(counterB()); // 1
counterA and counterB each have their own independent lexical environment.
7. Higher-Order Functions and Function Composition
Function composition (Function Composition) is an important concept in functional programming.
Its core is to connect multiple simple functions to form a new composite function.
7.1 Mathematical Representation of Function Composition
Suppose there are two functions:
Then they can be composed as:
After composition, we get:
Note that function composition executes from right to left: first execute g, then execute f.
7.2 Implementing compose
function compose(...functions) {
return function (value) {
return functions.reduceRight(
(result, fn) => fn(result),
value
);
};
}
const addOne = x => x + 1;
const double = x => x * 2;
const square = x => x * x;
const pipeline = compose(
square,
double,
addOne
);
console.log(pipeline(3)); // 64
Execution order:
pipeline(3)
→ addOne(3)
→ 4
→ double(4)
→ 8
→ square(8)
→ 64
Here, compose itself is a higher-order function:
- It receives multiple functions as arguments.
- It returns a new composite function.
7.3 compose and pipe
The core difference between the two is the execution direction.
| Function | Execution direction | Example |
|---|---|---|
| compose | From right to left | f(g(h(x))) |
| pipe | From left to right | h(g(f(x))) |
One way to implement pipe:
function pipe(...functions) {
return function (value) {
return functions.reduce(
(result, fn) => fn(result),
value
);
};
}
Function composition can break down complex business logic into multiple small functions, so that each function has a single responsibility and is easy to test and reuse.
Note that composed functions usually require the output type of the previous function to be usable as the input type of the next function. Asynchronous functions, exception handling, and functions with multiple parameters require additional composition rules to be designed.
VIII. Typical Application Scenarios of Higher-Order Functions
8.1 Decorator Pattern
Higher-order functions can wrap existing functions to add extra behavior without directly modifying the original function implementation.
function withLogging(fn) {
return function (...args) {
console.log("函数开始执行");
const result = fn(...args);
console.log("函数执行结束");
return result;
};
}
function add(a, b) {
return a + b;
}
const loggedAdd = withLogging(add);
console.log(loggedAdd(10, 20));
withLogging receives a function and returns a new function.
Typical applications:
- Logging.
- Performance monitoring.
- Permission checks.
- Caching.
- Parameter validation.
- Counting the number of calls.
Note: The implementation above is suitable for synchronous functions. For asynchronous functions, you need to correctly handle Promise fulfillment, rejection, and return values; you cannot simply assume that the function returning means the task is complete.