Javascript: Currying
What is currying?
In order to speak about currying we have to talk about functional programming. Function programming is becoming somewhat of a buzz word in terms of a paradigm shift in programming. What functional programming is, is the process of programming with pure functions, avoiding any side effects and shared state. Out of this paradigm concepts like currying are born. So what exactly is currying? Currying is a way in which we can transform a function that takes in multiple arguments into a series of partials. In other words a function which is usually called in this manner: f(a, b) can be transformed into be called like this f(a)(b). Lets look at the example below.
In our example we have a simple function multiply that takes in two arguments a and b and returns a * b. When we invoke our function with the arguments 8 and 20 we are returned an integer of 120. Simple.
Get Kevin Lai’s stories in your inbox
Join Medium for free to get updates from this writer.
In our curryMultiply function we see that it takes in one parameter a and it returns another function that takes in one parameter b, within this callback function it returns a * b. When the arguments 8 and 20 (invoked: curryMultiply(8)(20)) we still get 160 as our answer but what is the point of writing functions out in this way?
Currying separates our functions into partials, partials are “functions that return functions with some already predefined arguments and need some arguments to be completed.” This allows us to save the partials as separate variables giving us the same functionality without the repetition. Lets look at this example:
In our example above we want our function to multiply the second argument passed in by 3, so we want our function to multiply the second parameter b by three. What we can do is create a partial by invoking our function with one argument (3) and saving it to a variable multiplyByThree. This saves the function definition function(b){ return a * b } (a = 3) to the variable multiplyByThree so when we invoke multiplyByThree with an argument it will multiply that argument by three. In our example we invoke multiplyByThree with the argument 30 passed in and it returns 90. With currying we allow our function to be clearly stated. We can create multiple partials with different functionality and invoke them in a way that is cleaner and more legible.








