Currying in JavaScript

Rajan V
codeburst
Published in
2 min readSep 18, 2017

--

Explaining currying with examples.

In this post, We are going to see

  • What is currying?
  • Why it’s useful?
  • How to convert an existing function to curried version?
  • How does currying work?

Currying is a technique of evaluating function with multiple arguments, into sequence of function with single argument.

In other words, when a function, instead of taking all arguments at one time, takes the first one and return a new function that takes the second one and returns a new function which takes the third one, and so forth, until all arguments have been fulfilled.

That is, when we turn a function call add(1,2,3) into add(1)(2)(3) . By using this technique, the little piece can be configured and reused with ease.

Why it’s useful ?

  • Currying helps you to avoid passing the same variable again and again.
  • It helps to create a higher order function. It extremely helpful in event handling. See the blog post for more information.
  • Little pieces can be configured and reused with ease.

Let’s look at a simple add function. It accepts three operands as arguments, and returns the sum of all three as the result.

function add(a,b,c){
return a + b + c;
}

You can call it with too few (with odd results), or too many (excess arguments get ignored).

add(1,2,3) --> 6 
add(1,2) --> NaN
add(1,2,3,4) --> 6 //Extra parameters will be ignored.

How to convert an existing function to curried version?

The curry function does not exist in native JavaScript. But library like lodash makes it easier to convert a function to curried one.

//import or load lodashvar abc = function(a, b, c) {
return a + b + c;
};

var curried = _.curry(abc);
var addBy2 = curried(2);console.log(addBy2(0,0));
// => 2
console.log(addBy2(1,1));
// => 4
console.log(curried(4)(5)(6));
// => 15

See it in action in below pen,

How does currying work?

Currying works by natural closure.The closure created by the nested functions to retain access to each of the arguments.So inner function have access to all arguments.

Note: We can achieve the same behavior using bind.The problem here is we have to alter this binding.

var addBy2 = abc.bind(this,2);
console.log(addBy2(0,0));
// => 2

And that’s it for currying. I hope you have learned something new about this technique!. Do you have an example of currying that you like to share ?. If so, please leave it as a gist or code in comments. Thanks !!!

--

--