JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Javascript Interview: Function Composition: pipe()

Eishta Mittal
JavaScript in Plain English
3 min readFeb 24, 2025

--

What is function composition ?

In JavaScript, function composition is the practice of combining two or more functions to create a new function. The idea is similar to mathematical function composition: you apply one function to the result of another.

For example, if you have two functions f and g, the composition of f and g, written as f(g(x)), means that the result of g(x) is passed as an argument to f.

// Two simple functions
const add2 = (x) => x + 2;
const multiplyBy3 = (x) => x * 3;

// Function composition
const compose = (f, g) => (x) => f(g(x));

// Compose add2 and multiplyBy3
const add2ThenMultiplyBy3 = compose(multiplyBy3, add2);

console.log(add2ThenMultiplyBy3(5)); // Result: 21

Interview Question

You are asked to create a pipe() function, which chains multiple functions together to create a new function.

Suppose we have some simple functions like this

const times = (y) =>  (x) => x * y
const plus = (y) => (x) => x + y
const subtract = (y) => (x) => x - y
const divide = (y) => (x) => x / y

You have to create a pipe function in JavaScript that takes an array of functions and returns a new function. This new function, when called with an initial value, will apply each of the functions in the array to the value in order, from left to right.

When the pipe function is called with the array:

pipe([
times(2),
times(3)
])

It should return a function that, when invoked with an argument (say x = 5), applies the times(2) function first, then the times(3) function, and returns the result:

  • First, times(2)(5) is 5 * 2 = 10
  • Then, times(3)(10) is 10 * 3 = 30 So, calling the result with 5 will return 30

Solution

Lets break down the problem —

  • The pipe function should take an array of functions.
  • Each function in the array should be applied to the result of the previous function.
  • The order of functions in the array matters (left to right).

--

--

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Written by Eishta Mittal

Software Engineer passionate about Frontend Engineering

Responses (3)

Write a response