Currying is a technique in JavaScript that allows you to transform functions with multiple arguments into a sequence of functions, each taking one argument at a time. That is from
f(a, b, c)
tof(a)(b)(c)
.
This might sound overwhelming at first but should be very easy to understand with an example.
Suppose we want to multiply 2 numbers together. Assuming it is not straight forward, we can declare a function called multiply
as
function multiply(num1, num2) {
// pseudo complex logic
return num1 * num2;
}
But what if we want to generate variants which can either double or triple or quadruple a number?
One option could be to simply define each variant separately as
function double(num1) {
return multiply(2, num1);
}
Or we can be clever and use currying here
const generateMultiplier = function(multiplier) {
return function multiply(num) {
return multiplier * num;
}
}
This would give us the power to generate variants as we like
const double = generateMultiplier(2);
const result = double(2); // returns 4
Best of coding!
Top comments (4)
It's more readable if you use arrow functions:
I actually wanted to add a comment in between to assume that multiplying 2 numbers is a complex task
That's a very good (maybe best I've ever read) of Currying.
Thanks for sharing the article.
Is that closure? Is a curry a closure?