Currying in JavaScript š¤©
The great conversation I had this evening got me thinking about and revisiting a concept Iāve toyed with before ā currying. But this time, Iād like to explore it with you all!
Currying is an advanced technique for working with functions. Itās used not only in JavaScript but in other languages as well.
Currying is a process in functional programming in which we can transform a function with multiple arguments into the sequence of the Nesting function ( in the form of Closures chaining of closures).
In other words, when a function, instead of taking all arguments at one time, takes the first one and returns a new function that takes the second one and returns a new function that takes the third one, and so forth until all arguments have been fulfilled.
Currying is a transformation of functions that translates a function from callable as f(a, b, c) into callable as f(a)(b)(c).
currying just transforms the function not call it.
Get Prathameshbhalkeās stories inĀ yourĀ inbox
Join Medium for free to get updates fromĀ thisĀ writer.
Letās see an example first, to better understand what weāre talking about, and then practical applications.
Transformation of Function into Closures chaining format Below
Why itās useful?
- Currying helps us avoid passing the same variable again and again.
- It helps to create a higher-order function
Currying transforms a function with multiple arguments into a sequence/series of functions each taking a single argument.
As we see, function with the full arguments. Letās create a curried version of the function and see how we would call the same function (and get the same result) in a series of calls:
We could separate this sum(1)(2)(3) to understand it better:
Letās get to know how it works:
We passed 1 to the sum function:
It returns the function:
Now, sum1 holds the above function definition which takes an argument b.
We called the sum1 function, passing in 2:
The sum1 will return the third function:
The returned function is now stored in sum2 variable.
sum2 will be:
When sum2 is called with 3 as the parameter,
it does the calculation with the previously passed in parameters: a = 1, b = 2 and returns 6.
The last function only accepts c variable but will perform the operation with other variables whose enclosing function scope has long since returned. It works nonetheless because of Closure š„
Closure makes currying possible in JavaScript. I hope you have learned something new about currying!
Thanks for reading this article ā„ļø
If you have any question, please feel free to ping me on






