Function composition
In short: Function composition is a way to combine several functions into one, so that the result of one function becomes the input for the next.
Put simply:
composition is when you chain functions one after another to perform sequential transformations of data.
Detailed explanation
If there are functions f and g,
their composition compose(f, g) means:
compose(f, g)(x) === f(g(x))That is, g(x) runs first,
and then the result is passed into f().
Example 1 - manually
const toUpper = str => str.toUpperCase();
const exclaim = str => str + '!';
const shout = str => exclaim(toUpper(str));
console.log(shout('hello')); // "HELLO!"Here shout is a composition of functions toUpper and exclaim.
Example 2 - a universal compose function
function compose(...fns) {
return x => fns.reduceRight((v, fn) => fn(v), x);
}
const toUpper = str => str.toUpperCase();
const exclaim = str => str + '!';
const greet = str => `Hello, ${str}`;
const welcome = compose(exclaim, toUpper, greet);
console.log(welcome('bob')); // "HELLO, BOB!"compose runs functions from right to left:
compose(f3, f2, f1)(x) → f3(f2(f1(x)))
Example 3 - using pipe (left to right)
For readability, the opposite order is often used - pipe:
const pipe = (...fns) => x => fns.reduce((v, fn) => fn(v), x);
const result = pipe(
greet,
toUpper,
exclaim
)('bob');
console.log(result); // "HELLO, BOB!"pipe(f1, f2, f3)(x) → f3(f2(f1(x))),
but reads left to right, like a natural data flow.
Why composition is useful
Makes code declarative and readable Lets you build complex transformations from simple functions Increases reusability and testability It is the foundation of functional programming
Analogy
Imagine a conveyor belt:
input → function A → function B → function C → resultComposition lets you assemble this conveyor belt into a single function.
SUMMARY
| Property | Function composition |
|---|---|
| What it does | Combines several functions into one chain |
| Direction | Usually right to left (compose) or left to right (pipe) |
| Formula | compose(f, g)(x) = f(g(x)) |
| Benefits | Purity, reusability, readability |
| Example | compose(toUpper, trim)(str) |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.