DEV Community

Cover image for Functional Composition in JavaScript
Travis van der F.
Travis van der F.

Posted on

Functional Composition in JavaScript

Also known as function pipelines.

Functional composition is the idea of creating a new function by passing the output of one function directly into another. It allows complex behavior to emerge from small, simple pieces. It can be pictured as a relay race where one runner hands the baton to the next. Each function does its part, and the final result comes from their combined flow.

Instead of writing: Math.sqrt(minusOne(double(square(42))));

It can be rewritten to be more readable and modular by looping over an array of functions.

Defining simple functions (actions):

const double   = x => x * 2;
const minusOne = x => x - 1;
const square   = x => x * x;
Enter fullscreen mode Exit fullscreen mode

These small arrow functions:

  • double(x): multiplies by 2
  • minusOne(x): subtracts 1
  • square(x): multiplies a number by itself
  • Math.sqrt: built-in function taking the square root

Then building an array from these functions:

const functions = [
  square,
  double,
  minusOne,
  Math.sqrt,
];
Enter fullscreen mode Exit fullscreen mode

Order here matters too. Keep in mind that it's not calling the functions here; instead, it's storing their references in an array.

Next, call each function (in order) with a starting value defined (as a number):

let result = 42; // starting magic number

for (const fn of functions) {
  result = fn(result);
}
Enter fullscreen mode Exit fullscreen mode

This loop:
1. Takes the current result.
2. Passes it into the next function.
3. Stores the output back into the result.

Which will perform as:

result = square(42)
result = double(result)
result = minusOne(result)
result = Math.sqrt(result)
Enter fullscreen mode Exit fullscreen mode

To understand this fully, let's compute the steps:

  • Step 1: square(42) = 42 * 42 = 1764
  • Step 2: double(1764) = 1764 * 2 = 3528
  • Step 3: minusOne(3528) = 3528 - 1 = 3527
  • Step 4: Math.sqrt(3527) = ≈ 59.380

And so, the final output and final code:

const double   = x => x * 2;
const minusOne = x => x - 1;
const square   = x => x * x;

const functions = [
  square,
  double,
  minusOne,
  Math.sqrt,
];

let result = 42; // starting number

for (const fn of functions) {
  result = fn(result);
}

console.log('The answer is ' + result);
// The answer is 59.380217
Enter fullscreen mode Exit fullscreen mode

Top comments (0)