Skip to main content

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:

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

That is, g(x) runs first, and then the result is passed into f().


Example 1 - manually

javascript
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

javascript
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:

javascript
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:

javascript
input → function Afunction Bfunction C → result

Composition lets you assemble this conveyor belt into a single function.


SUMMARY

PropertyFunction composition
What it doesCombines several functions into one chain
DirectionUsually right to left (compose) or left to right (pipe)
Formulacompose(f, g)(x) = f(g(x))
BenefitsPurity, reusability, readability
Examplecompose(toUpper, trim)(str)

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.