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);
  6. }
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:

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

Disadvantages of currying

Please share your feedback / comments.