Higher Order Function Composition in JavaScript

Function composition is the act of combining one or many functions into a single function.

For example, lets say our compose function signiture looks like this:

function compose(functions) {
// our code to build the composition
};

// we can use this to craft our composition like so, where a, b, c are functions themselves
const composition = compose([a, b, c]);

// now composition can be used as a function which applies a -> b -> c to generate our output
composition(x);

How can we build this function?

function compose(functions) {
// return our inital anonymous function that simply takes in a value
return function (value) {
// iterate over our functions, applying them to value in the order given
for (let i = 0; i < functions.length; i++) {
// get our output from this function
let output = functions[i](value);
// set this to value so the next functions input will be this output
value = output;
}

// return our now transformed value
return value;
}
}

Let’s improve on this further by using forEach.

function compose(functions) {
// return our inital anonymous function that simply takes in a value
return function (value) {

// iterate over our functions, carrying `value` along
functions.forEach((f) => {
value = f(value);
});

// return our now transformed value
return value;
}
}

With that simple change we get something much cleaner. We can simplify even futher by using reduce, where we use the accumulator to store the output of the previous function, with it’s inital value being our input.

function compose(functions) {
return (value) => functions.reduceReduce((a, f) => f(a), value);
}

Update 7/21: Technically this should be reduceRight and not reduce.

Let’s take a look at a working example.

// the functional equivalent of Math.sqrt((x * 2) + 4)
const composition = compose([
(x) => x * 2,
(x) => x + 4,
Math.sqrt
]);

composition(4); // 3.4641016151377544
composition(8); // 4.47213595499958
composition(15); // 5.830951894845301
composition(16); // 6