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

The pipe Helper Function

Creating a pipe utility that applies functions left-to-right for more readable data flow.

The pipe Helper Function

You'll learn how to create a pipe utility that chains functions in left-to-right order, making data transformations easier to read and follow.

Why pipe?

In the previous lesson, you saw compose, which applies functions right-to-left (from the innermost outward). While mathematically elegant, it reads backward from how we naturally think: "take this data, do step 1, then step 2, then step 3."

pipe solves this by applying functions in the same order you write them—left to right.

Building the pipe Function

Just like compose, pipe takes multiple functions and returns a new function. The difference is the execution order:

const pipe = (...fns) => (initialValue) => 
  fns.reduce((value, fn) => fn(value), initialValue);

This uses reduce to pass the result of each function into the next, moving forward through the array.

Using pipe in Practice

const addTwo = (x) => x + 2;
const double = (x) => x * 2;
const square = (x) => x * x;

const transform = pipe(addTwo, double, square);

transform(3); 
// Step 1: addTwo(3) → 5
// Step 2: double(5) → 10
// Step 3: square(10) → 100

Notice how the operations flow naturally left-to-right, matching how you'd describe them: "add two, then double it, then square the result."

The Analogy

Think of pipe like an assembly line where items move forward through stations. Each station transforms the item and passes it to the next one in sequence.

Key Takeaway: The pipe helper applies functions left-to-right, creating readable data transformation pipelines that match natural reading order.