Course contentsShow
← JavaScript
Lesson 479 of 2,72312. Higher-Order FunctionsFree lesson

The compose Helper Function

Building a compose utility that applies functions right-to-left, matching mathematical notation.

The compose Helper Function

You'll learn how to build a reusable utility that chains functions together from right to left.

What It Is

In the last lesson, you saw manual composition with nested function calls like fn3(fn2(fn1(data))). A compose helper automates this pattern, creating a single function that applies multiple functions in sequence from right to left—just like mathematical notation f(g(x)).

Why Right-to-Left?

Mathematical convention reads f ∘ g as "apply g first, then f." Our compose helper follows this tradition: the rightmost function runs first, its output feeds the next function to the left, and so on.

Building the Helper

const compose = (...fns) => {
  return (value) => {
    return fns.reduceRight((acc, fn) => fn(acc), value);
  };
};

Here's what happens:

  • compose accepts any number of functions via rest parameters
  • It returns a new function that takes an initial value
  • reduceRight applies each function from right to left, passing results forward

Using It

const add5 = x => x + 5;
const double = x => x * 2;
const square = x => x * x;

const transform = compose(square, double, add5);

console.log(transform(3));  // 64
// Flow: 3 → add5 → 8 → double → 16 → square → 256... wait, let me recalculate
// 3 → add5 → 8 → double → 16 → square → 256 (correct)

Actually: 3 + 5 = 8, × 2 = 16, squared = 256. The rightmost (add5) runs first!

Key Takeaway: The compose helper encapsulates right-to-left function chaining into a reusable utility, making complex transformations cleaner and easier to reason about.