arrow_left_alt Back to Blog

2Minutes: Compose In JavaScript

calendar_today August 6, 2026 | timer 3 min read |

In the last post, we said reduce shouldn’t go around pretending to be map or filter. There’s one job, though, that reduce‘s sibling method was basically built for: compose.

What is Compose?


compose takes a handful of small functions and glues them into one bigger function, where the output of one becomes the input of the next.

const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);

const greet = name => `Hello, ${name}`;
const exclaim = str => str + "!!!";
const shout = str => str.toUpperCase();

const dramaticGreeting = compose(shout, exclaim, greet);

dramaticGreeting("Sam");
// greet runs first:   "Hello, Sam"
// then exclaim:        "Hello, Sam!!!"
// then shout:           "HELLO, SAM!!!"

Notice the engine under the hood: reduceRight. Instead of walking the function list left to right like a normal reduce, reduceRight starts from the rightmost function and works backward — which is exactly why greet, listed last, is actually the first one to touch your input.

The Trap: Compose Reads Backwards


This is the part that trips almost everyone up the first time. You’d naturally assume compose(shout, exclaim, greet) runs shout first, because it’s written first. It doesn’t. compose mirrors old math notation, f(g(h(x))) — the function closest to the input, greet, always runs first, even though it’s sitting last in the list.

If that backwards reading order bothers your team, there’s a mirror twin called pipe, built the exact same way but with plain reduce instead of reduceRight:

const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x);

const dramaticGreetingPipe = pipe(greet, exclaim, shout);
// same result, but now the list reads top to bottom in the order it actually runs

The takeaway for today is: compose isn’t magic, it’s reduceRight wearing a trench coat — and if right-to-left order ever confuses your team, pipe does the identical job left to right.

That’s 2Minutes Concept, see you in the next one!

Sources


https://www.geeksforgeeks.org/javascript/a-quick-introduction-to-pipe-and-compose-in-javascript

https://www.freecodecamp.org/news/pipe-and-compose-in-javascript-5b04004ac937

index.php