# Currying in Javascript

Jul 05, 2020Javascript as a functional programming have lots of concepts to offer which aren't popular among many new developers. One of such concept is Currying.

Currying is the technique of converting a function that takes multiple arguments into a sequence of functions that each take a single argument - Wikipedia

Currying technique was invented by Haskell Curry and it had been widely used in mathematics and computer science. The main advantages of using Currying technique are

- Code Reusability
- Less Error prone

Let us imagine that you're building an eCommerce application within which we'll create a simple function like below to calculate total of an item including tax

Above function takes subtotal and tax as its arguments and returns the total amount. Now, for calculating the total for each item in your imaginary cart, you would do something like this

If you notice deeply in the above code, you can clearly see that tax argument is being repeated on each calculation. In the future, if you wish to change the tax, you have to do multiple edits and had you missed at one place it might affect your revenue.

Let's fix this with currying technique now

At first, this might seem scary. But do not worry, it's very simple. We have to start with the last argument as the first argument in currying technique and result of first function will be a function which would take the second argument. So, until the last argument is passed it'll be kept on returning the function and when final argument is passed, it would return the desired result.

Now, let's calculate the total for our items on the cart again

Here, you can clearly see what's happening.

- We have defined tax in one place and we have been using amount(operates as a function) to calculate the total
- Since we have defined tax only at one place, tomorrow if you wish to change tax, you simply have to change at one place and it'll work like magic.

Now that you have understood the concept, let's rewrite the above currying technique in ES6

Whoa! Just single line. Pretty neat right?

Thats all is currying! It's very simple and efficient way of writing code.