Functional Composition in JavaScript
Source: Dev.to
Introduction
Functional composition, also known as function pipelines, lets you chain simple functions together to create more readable and modular code.
Defining Simple Functions
const double = x => x * 2;
const minusOne = x => x - 1;
const square = x => x * x;
double(x): multiplies by 2minusOne(x): subtracts 1square(x): multiplies a number by itselfMath.sqrt: built‑in function that returns the square root
Building the Function Pipeline
Store the function references in an array—no calls are made at this point.
const functions = [
square,
double,
minusOne,
Math.sqrt,
];
Executing the Pipeline
Start with an initial value and apply each function in order.
let result = 42; // starting number
for (const fn of functions) {
result = fn(result);
}
The loop:
- Takes the current
result. - Passes it into the next function (
fn). - Stores the output back into
result.
The sequence of calls is equivalent to:
result = square(42);
result = double(result);
result = minusOne(result);
result = Math.sqrt(result);
Step‑by‑Step Calculation
| Step | Operation | Result |
|---|---|---|
| 1 | square(42) | 1764 |
| 2 | double(1764) | 3528 |
| 3 | minusOne(3528) | 3527 |
| 4 | Math.sqrt(3527) | ≈ 59.380 |
Full Code Example
const double = x => x * 2;
const minusOne = x => x - 1;
const square = x => x * x;
const functions = [
square,
double,
minusOne,
Math.sqrt,
];
let result = 42; // starting number
for (const fn of functions) {
result = fn(result);
}
console.log('The answer is ' + result);
// The answer is 59.380217...