Currying in javascript

Currying in javascript

Currying is a very important concept which is found in a lot of programming languages. For example, Scala has a native currying function.

What is currying?

Currying in programming language means partial execution of a function. In simple words, currying means breaking down a function which takes more number of arguments into series of functions which take lesser arguments. The results of these functions are stored so that the every time you want to add some more arguments in the processing of the main function, you don’t have to do it from scratch. You have the results of previous function executions to which you can add newer arguments and get your task executed.

To understand better consider a function which calculates the average of n number of arguments where n is not known at the beginning. A traditional way of writing a function for this would be to make use of arguments object to access the arguments passed to the function since the number of arguments are not known prior to execution.


Now suppose you want to add a few more numbers to this list for calculating the average. You will have to add these numbers to the list again and execute the average calculating function. The drawback here is that calculation of average is a very costly task. Now when your numbers increase you are executing the function again on all those numbers as well for which the calculation was already done. This is unnecessary.

This unnecessary work can be avoided by using currying in javascript which allows for partial execution of the function using a set of arguments which you know will be used for your computations. You can add the other arguments to the curry function which stores the earlier execution in a closure thus avoiding unnecessary execution.

Use Closure for currying in javascript

Javascript does not have a native currying function. But javascript has a very powerful concept of Closures which is a great tool for building a currying function.

Consider the same average example. Say you know three parameters ‘4, 2 and 6’ that will always be present in the calculation of the average. Apart from these there might be n number of parameters that might be added to the list. You can build a currying function in which you can store the sum of ¬†‘4, 2 and 6’ in a closure. This sum will be available for any subsequent invocation of the average function without the need to pass them again and without the need of its computation again.

In the above example you can see that ‘outer function’ will be printed in console only 3 times, that is the outer function will be executed only once for the first three arguments that are initially provided. The result of the other function execution (sum of the initial parameters provided) is stored in closure and this will be available any number of times you want to use it, without the need to execute it again.

Comments are closed.