Function Currying in Javascript
If you ever gave an interview for frontend developer position. You might have already been asked about what is function currying. So In this post we will try to answer this question with some example which will help us in next interview.
What is currying ?
Currying is a technique of working with function. It transforms the functions being callable like this g(f(x))
to f(x)(y)
. Which simply means getting arguments one at time then returning its value and then taking another argument and returning its value.
Currying can be used in other languages as well but in this post we are going to focus on Javascript.
Now let see how currying looks like in Javascript.
Let's try to multiply two number using two functions one will take arguments all at once while other will use currying technique.
Function without currying
function multiply(a, b) {
console.log(a, b);
}
multiply(3,7); // 21
In the above example we are passing argument all at once.
Function with currying
function multiply(a){
return function(b){
console.log(a*b);
}
}
// or we can write same function like this i am just renaming it to multi
const multi = (a) =>(b) => console.log(a*b);
multiply(3)(7); // 21
multi(3)(7); //21
Let's see more advance example where we will pass a function as an arguments. In this example we will calculate volume.
function volume(f) {
return function(a) {
return function(b) {
return function(c) {
return f(a, b) * c
}
};
};
}
// usage
function area(a, b) {
return a * b;
}
let curriedSum = volume(area);
alert( curriedSum(3)(2)(2) ); // 12
Here we are executing the area function at last return a
, b
and c
are present in its lexical scope.