Functional Composition in JavaScript

Published: (December 10, 2025 at 01:33 PM EST)
2 min read
Source: Dev.to

Source: Dev.to

Introduction

Functional composition, also known as function pipelines, lets you chain simple functions together to create more readable and modular code.

Defining Simple Functions

const double   = x => x * 2;
const minusOne = x => x - 1;
const square   = x => x * x;
  • double(x): multiplies by 2
  • minusOne(x): subtracts 1
  • square(x): multiplies a number by itself
  • Math.sqrt: built‑in function that returns the square root

Building the Function Pipeline

Store the function references in an array—no calls are made at this point.

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

Executing the Pipeline

Start with an initial value and apply each function in order.

let result = 42; // starting number

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

The loop:

  1. Takes the current result.
  2. Passes it into the next function (fn).
  3. Stores the output back into result.

The sequence of calls is equivalent to:

result = square(42);
result = double(result);
result = minusOne(result);
result = Math.sqrt(result);

Step‑by‑Step Calculation

StepOperationResult
1square(42)1764
2double(1764)3528
3minusOne(3528)3527
4Math.sqrt(3527)≈ 59.380

Full Code Example

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...
Back to Blog

Related posts

Read more »

First-Class Functions in JavaScript

Introduction For developers learning JavaScript, the term first‑class functions appears frequently in discussions and documentation. In JavaScript, functions a...

Functions in javascript

What is a Function? A function is a block of code designed to perform a specific task. It runs only when it is called. javascript function add { console.log'He...