Launching Drycomponents - Get Free HTML/React Components built using TailwindCSS

Function Composition in Javascript

In my previous two articles, we saw techniques like Currying and Pure functions in Javascript. In this article, I'll explain you what is function composition in Javascript

In computer science, function composition is an act or mechanism to combine simple functions to build more complicated ones. - Wikipedia

Seems complicated to understand? Let's start off with a simple example. Assume there are few items on your cart which are out of stock. And you wanted to exclude those and calculate the total only for the in stock items. So you would be performing something like this

Here, we have not used any functions to get our desired output, which means our code can't be reused in the future and it'll be harder for us to test our code.

Now, we are going to perform the following

  1. Break our solution into smaller functions
  2. Deal one function at a time
  3. Put them back together so it works as a whole unit

Let's get started

Perfect! Did you notice what have we achieved here? We have not only created separate functions for reusing them, but also they are pure functions which means they don't have any side effects.

ES6

Now, let's tweak our solution using the ES6

Elegant right? That is all Function Composition in Javascript is. Here, we broke our solution into two functions, and have put them back together to work as a whole unit. Now our functions are pure in nature, reusable and easy to test.

See you in another article! Happy Coding!

Would like to hear more from me?

Consider Signing up. No spam ever.

Name

Email

Topic