Understand Currying Function In JavaScript
Posted By : Ankit Uniyal | 30-May-2018
In this blog, we will discuss
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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Ankit Uniyal
Ankit has knowledge in Javascript, NodeJS, AngularJS and MongoDB also have experience in using AWS Services.