Back to series
· 8 min read

Higher-Order Functions & Function Composition


I. Higher-Order Functions

1. What Is a Higher-Order Function?

A higher-order function is a function that satisfies either of the following conditions:

  1. It takes one or more functions as arguments.
  2. It returns a function as its return value.

This means functions can not only execute logic but also be passed around, stored, and dynamically created like ordinary data.

For example:

function applyOperation(value, operation) {
    return operation(value);
}

function double(x) {
    return x * 2;
}

console.log(applyOperation(5, double)); // 10

Here, applyOperation takes the operation function as an argument, so it is a higher-order function.

Another example:

function createMultiplier(factor) {
    return function (value) {
        return value * factor;
    };
}

const double = createMultiplier(2);
const triple = createMultiplier(3);

console.log(double(5)); // 10
console.log(triple(5)); // 15

createMultiplier returns a function, so it is also a higher-order function.

2. Functions Are First-Class Citizens

Higher-order functions are built on the foundation that functions are first-class citizens (First-Class Function).

Being a first-class citizen means functions can participate in language operations like ordinary values:

  • Being assigned to variables.
  • Being passed as arguments.
  • Being returned as function return values.
  • Being stored in arrays, objects, or other data structures.
  • Being dynamically created and called at runtime.

For example:

const add = (a, b) => a + b;

const operation = add;

const operations = [
    (x) => x + 1,
    (x) => x * 2,
    (x) => x * x
];

console.log(operation(2, 3)); // 5
console.log(operations[1](5)); // 10

Two concepts need to be distinguished:

Concept Meaning
First-class function (First-Class Function) Functions can be manipulated like ordinary values
Higher-order function (Higher-Order Function) A function takes a function or returns a function

First-class functions are a capability provided by the language, while higher-order functions are an abstraction built on that capability.

3. Common Higher-Order Functions

Higher-order functions are widely found in standard libraries, collection operations, asynchronous programming, and event systems.

3.1 map: Mapping and Transformation

map applies a transformation function to each element in a collection and returns a new collection.

const numbers = [1, 2, 3, 4];

const result = numbers.map(x => x * 2);

console.log(result); // [2, 4, 6, 8]

Core semantics:

  • Input: a collection and a transformation function.
  • Operation: apply the function to each element.
  • Output: a new collection composed of the transformation results.

Mathematically, this can be expressed as:

map(f,[x_1,x_2,\ldots,x_n]) = [f(x_1),f(x_2),\ldots,f(x_n)]

3.2 filter: Conditional Filtering

filter filters collection elements according to a predicate function.

const numbers = [1, 2, 3, 4, 5, 6];

const result = numbers.filter(x => x % 2 === 0);

console.log(result); // [2, 4, 6]

Elements for which the predicate function returns a truthy value are kept.

3.3 reduce: Reduction

reduce gradually reduces multiple elements in a collection to a single result.

const numbers = [1, 2, 3, 4];

const sum = numbers.reduce(
    (accumulator, current) => accumulator + current,
    0
);

console.log(sum); // 10

Its basic form is:

reduce(f,initial,[x_1,\ldots,x_n])

Each time the reduction function is called, the current accumulated value and the next element are passed in.

3.4 forEach: Iteration and Execution

forEach applies a function to each element in a collection and is usually used to perform side effects.

const users = ["Alice", "Bob", "Carol"];

users.forEach(user => {
    console.log(`Hello, ${user}`);
});

Its important difference from map is that forEach is not used to produce a new transformed collection, and its return value is usually undefined.

3.5 Function Factories: Returning Functions

A function factory determines the behavior of the function it generates through its parameters.

function createValidator(min, max) {
    return function (value) {
        return value >= min && value <= max;
    };
}

const validateAge = createValidator(18, 60);

console.log(validateAge(25)); // true
console.log(validateAge(15)); // false

The returned function retains access to min and max, which involves the closure mechanism.

4. The Execution Mechanism of Higher-Order Functions

Higher-order functions themselves have no special low-level execution instructions. They rely on the language's function objects, calling mechanism, and scoping rules.

Take a function passed as a parameter, for example:

function execute(value, callback) {
    const result = callback(value);
    return result;
}

function square(x) {
    return x * x;
}

const result = execute(5, square);

The execution process:

flowchart TD
    A["Call execute(5, square)"] --> B["Pass in value and callback"]
    B --> C["callback points to square"]
    C --> D["Call callback(value)"]
    D --> E["Execute square(5)"]
    E --> F["Return 25"]
    F --> G["execute returns 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:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

There are a few things to note here:

  • When you pass a function, what is passed is a reference to the function, not the result of executing it.
  • The function body only executes when a function call occurs.
  • The timing of when the callback function executes is determined by the caller's implementation.
  • A callback function can execute synchronously, or it can execute after an asynchronous task completes.

5. Higher-Order Functions and Closures

Higher-order functions are often used together with closures, but the two are not the same concept.

A closure is the combination of a function and the lexical environment it captures. Even after a function leaves its original outer function scope, it can still access the captured variables.

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

Here:

  • createCounter is a higher-order function because it returns a function.
  • The returned anonymous function is a closure because it accesses count in the outer scope.
  • The state of count is preserved across multiple calls.

A higher-order function does not necessarily produce a closure, and a closure is not necessarily returned by a higher-order function.


II. Function Composition

1. What Is Function Composition

Function composition is the act of connecting multiple functions so that the output of one becomes the input of another, thereby building a new function.

Suppose there are two functions:

f:A\rightarrow B
g:B\rightarrow C

Then they can be composed as:

g\circ f:A\rightarrow C

This means executing f first, then g:

(g\circ f)(x)=g(f(x))

For example:

const addOne = x => x + 1;
const double = x => x * 2;

const result = double(addOne(5));

console.log(result); // 12

Order of execution:

flowchart LR
    A["Input 5"] --> B["addOne"]
    B --> C["Get 6"]
    C --> D["double"]
    D --> E["Get 12"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

The core idea of function composition is to break complex logic into multiple small functions, each with a single responsibility, and then build the complete behavior through composition.

2. compose: composing from right to left

compose is a common way to implement function composition.

Multiple functions are executed in order from right to left:

compose(f,g,h)(x)=f(g(h(x)))

Implementation:

const compose = (...fns) =>
    value => fns.reduceRight(
        (result, fn) => fn(result),
        value
    );

const addOne = x => x + 1;
const double = x => x * 2;
const square = x => x * x;

const calculate = compose(square, double, addOne);

console.log(calculate(3)); // 64

Execution process:

  1. addOne(3) yields 4.
  2. double(4) yields 8.
  3. square(8) yields 64.

Note: the order of the arguments to compose is the reverse of the actual execution order.

3. pipe: composing from left to right

pipe shares the same core idea as compose; the difference lies in the direction of function execution.

pipe(f,g,h)(x)=h(g(f(x)))

Implementation:

const pipe = (...fns) =>
    value => fns.reduce(
        (result, fn) => fn(result),
        value
    );

const addOne = x => x + 1;
const double = x => x * 2;
const square = x => x * x;

const calculate = pipe(addOne, double, square);

console.log(calculate(3)); // 64

pipe is closer to the processing order of natural language, and is usually easier to read for complex data-processing flows.

4. The difference between compose and pipe

Comparison dimension compose pipe
Execution direction Right to left Left to right
Argument order The function executed first comes last The function executed first comes first
Mathematical expression f(g(h(x))) h(g(f(x)))
Implementation approach reduceRight reduce
Reading convention Mathematical function composition style Pipeline processing style

Both require that the output type of one function connects with the input type of the adjacent function.

5. Mathematical properties of function composition

Function composition is not only a way of organizing code; it also has well-defined mathematical properties.

5.1 Associativity

Function composition satisfies the associative law:

(f\circ g)\circ h=f\circ(g\circ h)

As long as the function types connect correctly, changing how the composition is grouped does not change the result.

This means:

const left = compose(f, compose(g, h));
const right = compose(compose(f, g), h);

Assuming consistent function semantics, the two are equivalent.

However, note that associativity does not mean the order in which functions are executed can be changed arbitrarily.

5.2 Non-commutativity

Generally:

f\circ g\neq g\circ f

For example:

const addOne = x => x + 1;
const double = x => x * 2;

console.log(double(addOne(3))); // 8
console.log(addOne(double(3))); // 7

Function composition cannot be reordered arbitrarily, because execution order affects the final result.

5.3 Identity Function

The identity function satisfies:

id(x)=x

When composed with other functions, it does not change the function's behavior:

f\circ id=f
id\circ f=f

JavaScript implementation:

const identity = x => x;

const compose = (f, g) => x => f(g(x));

const addOne = x => x + 1;

const result = compose(addOne, identity)(5);

console.log(result); // 6

The identity function plays an important role in generic processing, function composition abstraction, and functional library design.


III. Relationship Between Higher-Order Functions and Function Composition

Higher-order functions provide the ability to take functions as parameters and return functions as values, while function composition uses this ability to organize multiple functions into a new function.

Their relationship:

Dimension Higher-Order Function Function Composition
Core concept A function receives a function or returns a function Multiple functions are connected to form a new function
Main purpose Improve abstraction and reuse Organize complex logic
Typical operations map, filter, reduce, callbacks compose, pipe
Dependency Depends on first-class functions Usually implemented through higher-order functions
Application scenarios Callbacks, strategies, events, function factories Data transformation, business processes, pipeline processing

Not all higher-order functions are function composition, nor must all function composition be implemented through a generic compose.

For example, filter is a higher-order function, but it does not necessarily represent the composition of multiple functions.


IV. Practical Applications of Function Composition

1. Data Processing Pipeline

In real-world business, raw data often needs to be cleaned, transformed, and filtered.

const normalize = users =>
    users.map(user => ({
        ...user,
        name: user.name.trim().toLowerCase()
    }));

const filterActive = users =>
    users.filter(user => user.active);

const extractNames = users =>
    users.map(user => user.name);

const pipe = (...fns) =>
    value => fns.reduce(
        (result, fn) => fn(result),
        value
    );

const processUsers = pipe(
    normalize,
    filterActive,
    extractNames
);

const users = [
    { name: " Alice ", active: true },
    { name: " Bob ", active: false },
    { name: " Carol ", active: true }
];

console.log(processUsers(users));
// ["alice", "carol"]

The business logic is split into three independent functions:

  • normalize: Normalize data.
  • filterActive: Filter active users.
  • extractNames: Extract user names.

Each function can be tested independently and reused in other business processes.

2. Functional Middleware

Middleware usually wraps existing functions through higher-order functions, adding extra behavior without modifying the original business logic.

function withLogging(fn) {
    return function (...args) {
        console.log("开始执行");

        const result = fn(...args);

        console.log("执行完成");

        return result;
    };
}

function calculate(a, b) {
    return a + b;
}

const loggedCalculate = withLogging(calculate);

console.log(loggedCalculate(2, 3));

withLogging takes a function and returns a wrapped function.

This is a typical decorator-style higher-order function application.

Note that this example only works for synchronous functions. If fn returns a Promise, the current implementation will print “执行完成” before the Promise completes. For asynchronous functions, you need to wrap the Promise’s fulfillment and rejection.

3. Functional Error Handling

Higher-order functions can separate exception-handling logic from business logic.

function withErrorHandling(fn) {
    return function (...args) {
        try {
            return {
                success: true,
                data: fn(...args)
            };
        } catch (error) {
            return {
                success: false,
                error: error.message
            };
        }
    };
}

function divide(a, b) {
    if (b === 0) {
        throw new Error("除数不能为零");
    }

    return a / b;
}

const safeDivide = withErrorHandling(divide);

console.log(safeDivide(10, 2));
// { success: true, data: 5 }

console.log(safeDivide(10, 0));
// { success: false, error: "除数不能为零" }

This approach allows error-handling strategies to be reused across multiple functions.

However, exception-catching boundaries need to be designed sensibly. You should not swallow system-level errors or unrecoverable errors just to standardize the return format.

4. Function Composition and Asynchronous Processing

Synchronous function composition requires the output of each function to be usable as the input of the next function.