Gaurav Dubey
2 min readJan 27, 2021

--

Function Composition in JavaScript

Composition in JavaScript not a famous term in daily use but when you encounter the reactjs components.

composition is to combine simple functions to build more complicated ones.

Benefits of Composition

Because the concept of composition is such a large part of what makes React awesome and incredible to work with, let’s dig into it a little bit. Remember that composition is just combining simple functions together to create complex functions. There are a couple of key ingredients here that we don’t want to lose track of. These ingredients are:

  • simple functions
  • combined to create another function

Function composition is the point wise application of one function to the result of another. Developers do it in a manual manner every day when the nest functions:

compose = (fn1, fn2) => value => fn2(fn1(value))

But this is hard to read. There is a better way using function composition. Instead of reading them from inside out:

add2AndSquare = (n) => square(add2(n))

To get even more flexibility we can use the reduceRight function:

compose = (...fns) => (initialVal) => fns.reduceRight((val, fn) => fn(val), initialVal);

Reading compose from left to right allows a clear chaining of higher order functions. Real world examples are adding authentications, logging and context properties. It’s a technique that enables reusability on the highest level. Here are some examples how to use it:

// example
const add2 = (n) => n + 2;
const times2 = (n) => n * 2;
const times2add2 = compose(add2, times2);
const add6 = compose(add2, add2, add2);
times2add2(2); // 6
add2tiems2(2); // 8
add6(2); // 8

You might think this is advanced functional programming and it’s not relevant for frontend programming. But it’s also useful in Single Page Applications. For example you can add behavior to a React component by using higher order components:

function logProps(InputComponent) {
InputComponent.prototype.componentWillReceiveProps = function(nextProps) {
console.log('Current props: ', this.props);
console.log('Next props: ', nextProps);
};
return InputComponent;
}
// EnhancedComponent will log whenever props are received
const EnhancedComponent = logProps(InputComponent);

In conclusion function composition enables reusability of functionality at a very high level. If the functions are structured well it enables developers to created new behavior based upon existing behavior.

It also increases readability of implementations. Instead of nesting functions you can clearly chain functions and create higher order functions with meaningful names.

--

--