Composition
Function Composition is the process of combining multiple functions together so that the output of one function becomes the input of the next.
In simple words: Function composition lets you build complex operations by chaining small, reusable functions together.
Example Without Composition:
function double(x) {
return x * 2;
}
function square(x) {
return x * x;
}
const number = 5;
const result = square(double(number));
console.log(result); // Output: 100
This works fine, but when you have many functions, nesting them gets hard to read. Example With Composition:
function compose(f, g) {
return function (x) {
return f(g(x));
};
}
const doubleThenSquare = compose(square, double);
console.log(doubleThenSquare(5)); // Output: 100
Composing Multiple Functions:
function compose(...functions) {
return function (value) {
return functions.reduceRight((acc, fn) => fn(acc), value);
};
}
const add5 = (x) => x + 5;
const double = (x) => x * 2;
const square = (x) => x * x;
const composed = compose(square, double, add5);
console.log(composed(2)); // Output: 196
add5(2)→ 7double(7)→ 14square(14)→ 196
So compose(square, double, add5) runs right-to-left.
Composition vs Currying
| Concept | Description | Example |
|---|---|---|
| Currying | Breaks one multi-argument function into many single-argument functions | f(a, b) → f(a)(b) |
| Composition | Combines multiple single-argument functions into one | f(g(h(x))) |