DEV Community

Saksham Malhotra
Saksham Malhotra

Posted on

Let's make a curry!

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) to f(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;
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Or we can be clever and use currying here

const generateMultiplier = function(multiplier) {
    return function multiply(num) {
        return multiplier * num;
    }
}
Enter fullscreen mode Exit fullscreen mode

This would give us the power to generate variants as we like

const double = generateMultiplier(2);

const result = double(2); // returns 4

Enter fullscreen mode Exit fullscreen mode

Best of coding!

Top comments (4)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

It's more readable if you use arrow functions:

const generateMultiplier = multiplier => num => multiplier * num
Enter fullscreen mode Exit fullscreen mode
Collapse
 
saksham-malhotra profile image
Saksham Malhotra

I actually wanted to add a comment in between to assume that multiplying 2 numbers is a complex task

Collapse
 
raddevus profile image
raddevus

That's a very good (maybe best I've ever read) of Currying.
Thanks for sharing the article.

Collapse
 
abhiunx profile image
Abhishek Kharwar

Is that closure? Is a curry a closure?