Composition
Learn to combine small functions into bigger ones.
Composition
Composition combines small functions into a bigger function. The output of one function becomes the input of the next. This lets you split complex work into small, reusable pieces.
const addOne = x => x + 1;
const double = x => x * 2;
const result = double(addOne(3));Here addOne(3) runs first and produces 4, then double(4) runs and yields 8. The nested call is the composition of the functions.
compose and pipe
Two common helpers make composition easy. compose applies functions right to left: compose(f, g)(x) calls g first, then f.
const compose = (f, g) => x => f(g(x));pipe applies left to right: pipe(f, g)(x) calls f first, then g. pipe reads more naturally; compose is closer to math notation.
Exercise Write the compose helper
Write a function named compose. It takes two functions (f and g) and returns a new function that computes f(g(x)) for x. addOne and double are already defined. Then call const fn = compose(double, addOne); and console.log(fn(3));.
Show example solution
function compose(f, g) {
return x => f(g(x));
}
const fn = compose(double, addOne);
console.log(fn(3));
Test yourself
-
What does compose(f, g)(x) return?
const compose = (f, g) => x => f(g(x));- g(f(x))
- f(x) + g(x)
- f(g(x) + 1)
- f(g(x))
Show answer
f(g(x)) — Correct! compose applies g first, then f: f(g(x)).
-
A compose call that yields 8
const addOne = x => x + 1; const double = x => x * 2; // yields 8: const result = ____;Show answer
const addOne = x => x + 1; const double = x => x * 2; // yields 8: const result = compose(double, addOne)(3); -
Match compose and pipe directions
- compose(f, g)
- f(g(x))
- pipe(f, g)
- g(f(x))
- chaining .map
- ordered transform