What is function composition?

Function composition combines small functions into a new function where the output of one becomes the input of the next, so compose(f, g)(x) equals f(g(x)); it lets you build complex transformations from simple, reusable steps.

compose vs pipe

  • compose(f, g, h)(x) runs right to left: f(g(h(x))), matching mathematical notation.
  • pipe(h, g, f)(x) runs left to right, which most people find easier to read because it follows the data flow.

Why it helps

  • Each step is a small, pure, individually testable function.
  • Pipelines read like a list of steps: trim, lower-case, slugify.
  • Steps can be reused and recombined.

Requirements

Each function should take one input and return one output (curried helpers help here). Composition shines with pure functions, since side effects make the order and result harder to reason about.

Async pipelines

For functions that return promises, reduce with await: fns.reduce(async (acc, fn) => fn(await acc), Promise.resolve(x)).

Where you see it

  • Middleware chains (Express, Redux).
  • Higher-order components in older React code.
  • Data transformation utilities (Lodash flow, Ramda pipe).
  • A proposed pipeline operator (|>) has been discussed for years but is not part of the language yet, so libraries and helper functions are still the way.

Code example

js
1const pipe = (...fns) => (input) => fns.reduce((value, fn) => fn(value), input);
2const compose = (...fns) => (input) => fns.reduceRight((value, fn) => fn(value), input);
3
4// Small, single-purpose steps
5const trim = (s) => s.trim();
6const lower = (s) => s.toLowerCase();
7const stripAccents = (s) => s.normalize("NFD").replace(/[̀-ͯ]/g, "");
8const hyphenate = (s) => s.replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
9
10const slugify = pipe(trim, lower, stripAccents, hyphenate);
11console.log(slugify(" Héllo World: JS Composition! ")); // hello-world-js-composition
12
13// compose = same thing, read right to left
14const slugify2 = compose(hyphenate, stripAccents, lower, trim);
15console.log(slugify2("Café Menu") === slugify("Café Menu")); // true
16
17// Async pipeline
18const pipeAsync = (...fns) => (input) => fns.reduce(async (acc, fn) => fn(await acc), Promise.resolve(input));
19const fetchUser = async (id) => ({ id, name: "ada lovelace" });
20const titleCase = (u) => ({ ...u, name: u.name.replace(/\b\w/g, (c) => c.toUpperCase()) });
21const toCard = (u) => `#${u.id} ${u.name}`;
22console.log(await pipeAsync(fetchUser, titleCase, toCard)(7)); // #7 Ada Lovelace

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app