Currying in JavaScript
Hi Sir, do you have a moment to talk about currying? Well, I hope you do, because this is one of the most useful techniques when it comes to Functional Programming.
Ok, but first can you tell me what is currying?
Of course I do Sir, here’s the definition of currying according to Wikipedia:
In mathematics and computer science, currying is the technique of translating the evaluation of a function that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions, each with a single argument (partial application).
Don’t worry if you didn’t get it by now, it’s fine, you will surely understand what we’re talking about if you let me give some examples.
Give an example then!
As you wish!
Here we’re going to create a sum function that takes only one argument at a time.
Here’s what happens when running the code above:
When calling var onePlus = sum(1)
, you receive the secondFunction(b)
and assign it to the onePlus
variable.
There’s an important detail to pay attention here: the a
variable inside secondFunction
gets the value you’ve given as a parameter to the firstFunction
.
In a nutshell: imagine onePlus
is equivalent to the following:
After assigning secondFunction
to the onePlus
variable we’re calling it and passing 2
as an argument. This means that when we write onePlus(2)
we’re invoking secondFunction
using 2
as an argument.
In the example above we’ve used currying to add any number to 1
, now let’s suppose we need to add any number to 50, how would we do it?
This is awesome, can you give me one more example?
Of course I can.
Here’s the code:
In the example above we’re calling epicFunction
and then getting it’s result (which in this case is another function) and invoking it again passing another parameter.
For each call we’ve made the variables inside the innermost function are being assigned the values we pass to the outermost functions.
Just in case you still didn’t get it, I’m gonna show you what happens step by step:
Now ryanIsTheGreatest
is the same as:
If we do:
The variable greatestActor
will be the same as:
Finally, when doing:
greatestActorAlive
will contain the following string: Ryan Ghosling is the greatest actor alive.
In this post you should’ve learned:
- What is Currying
- How it works
- That Ryan Ghosling is the best actor alive