Let's make a curry!

saksham-malhotra

Saksham Malhotra

Posted on January 9, 2024

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!

đź’– đź’Ş đź™… đźš©
saksham-malhotra
Saksham Malhotra

Posted on January 9, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related