Voice of a Developer: JavaScript Currying - Part Fifteen

JavaScript is a language of the Web. This series of articles will talk about my observations learned during my decade of software development experience with JavaScript.

Before moving further let us look at the previous articles of the series:

Every programmer wants to write good & reusable code. Curry can help to achieve that.

Context

We’ve explored functional programming aspects of Javascript like closure, similarly another useful concept is currying. Here's some important information before I move ahead with currying.

Arity

Arity refers to the number of arguments a function can accept. And, you can have functions to take n number of arguments, which is called as variadic functions. And you can leverage arguments to slice into unary, binary arguments depending upon your requirement.

Example,

  1. function showArgs(a, b, c)  
  2. {  
  3.     var args = [].slice(arguments); // [] represent Array literal  
  4.     // you can also invoke as [].slice.call(arguments), both are same representation  
  5.     console.log(arguments.length);  
code

Currying

Let’s cook tasty functions!

We know that extra / excess params passed to a function is ignored and not processed. Hence, it goes wasted, also if you’ve too many params passed to function it. Look at this binary function.
  1. function sum(x, y) {  
  2. return x + y;  
  3. }
It could be written as,
  1. var add = sum(10);   
  2. add (20); // 30  
  3. add (55); // 65
Below is the debug mode of above code where values of x, y are mentioned,

code

Steps: 
  • sum function returns a function – this is closure implementation.
  • add – stores declaration as,
    1. function (y) {  
    2. return x + y;  
    3. }  
  • Now, whenever we invoke add (55) it calls above code and here is the value in watch.

    code

Now if your arguments grow then you could increase and it could turn like,

  1. function sumFour(w)   
  2. {  
  3.     return function(x)  
  4.     {  
  5.         return function(y)  
  6.         {  
  7.             return function(z)  
  8.             {  
  9.                 return w + x + y + z;  
  10.             }  
  11.         }  
  12.     }  
  13. }  
  14. sumFour(1)(2)(3)(4);  
Advantages of currying 
  • If you’re not aware of the parameters in advance, then you can store the partial result.

  • It doesn’t allow more than specified number of arguments, ex-

    code

    In above function if we pass (5) as extra argument then the function will throw an error.

Disadvantages of currying

  • It is not a good idea to use currying when the function has a lot of arguments.

  • Some people feel it's just another representation of way we write functions.

  • It is associated with partial application. We’ll cover partial application in some article as it’s beyond the scope of this article.

Please share your feedback / comments.

Up Next
    Ebook Download
    View all
    Learn
    View all