MediumFunctions📖 Theory Question

What is function composition and how do compose() and pipe() differ?

💡

Hint

Chain functions: output of one becomes input of next — compose=right-to-left, pipe=left-to-right

Full Answer

Function composition combines multiple functions where the output of one becomes the input of the next, building complex operations from simple pieces.

// compose — right to left (mathematical convention)
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);

// pipe — left to right (more readable)
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);

const trim      = str => str.trim();
const lowercase = str => str.toLowerCase();
const addBang   = str => str + '!';

// compose: addBang(lowercase(trim(x)))
const processC = compose(addBang, lowercase, trim);

// pipe: trim → lowercase → addBang
const processP = pipe(trim, lowercase, addBang);

processP('  Hello World  '); // 'hello world!'
processC('  Hello World  '); // 'hello world!'

// Without composition (harder to read as chain grows)
const manual = str => addBang(lowercase(trim(str)));
💡 compose() mirrors mathematical f∘g notation. pipe() reads like a Unix pipeline — more natural for most developers. Both are equivalent, just different argument order.

More Functions Questions

EasyWhat is the difference between call, apply, and bind?EasyHow do arrow functions differ from regular functions?EasyWhat is a pure function and why does it matter?EasyWhat are Higher-Order Functions (HOF)?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint