Understand Currying Function In JavaScript

Posted By : Ankit Uniyal | 30-May-2018

In this blog, we will discuss about currying function in JavaScript, currying is very useful in JavaScript, originally developed by Haskell Brooks Curry.

 

It is a way of evaluating function with multiple arguments i.e sequence of function with single argument.In a nutsell, it breaks down single function into a series of functions in which each takes single argument.Currying is native in languages such as Haskell and Scala, which are built around functional concepts. But currying isn’t built in by default to JavaScript.It also helps you to avoid passing the same variable again and again and to create a higher order function.Let's take a very simple example :

var add = function(a) {

    return function(b) {
        return a + b;
    }
};

var addToFive = add(5);

console.log(addToFive(1));    
        

Curry function does not exists in native JavaScript but we can convert a function into curried function using lodash library.

//import lodash library
var sampleFunction = function(a, b, c) {
  return a + b + c;
};
 
var curried = _.curry(sampleFunction);
var additionBy2 = curried(2);
console.log(additionBy2(0,0));
// => 2
console.log(additionBy2(1,1));
// => 4
console.log(curried(4)(5)(6));
// => 15   
        

It basically works using natural closure as it created by the nested functions to retain access to each of the arguments, thus inner function have access to all the arguments.

 

Thanks

About Author

Author Image
Ankit Uniyal

Ankit has knowledge in Javascript, NodeJS, AngularJS and MongoDB also have experience in using AWS Services.

Request for Proposal

Name is required

Comment is required

Sending message..