DEV Community

Cover image for Currying
Parwinder 👨🏻‍💻
Parwinder 👨🏻‍💻

Posted on

3 1

Currying

Currying is a technique in which you make a function that takes multiple arguments into a series of functions that each take only one argument. It is translating a function from callable as f(a, b, c, n) into callable as f(a)(b)(c)(n).

Let's start with an example of a function that takes two arguments.

const multiply = (a, b) => {
    return a * b;
}

console.log(multiply(4, 3)); // 12

We will convert this into a series of functions where each one takes only one argument (currying):

const multiply = (a) => {
    return (b) => {
        return a * b;
    }
}

console.log(multiply(4)(3)); // 12

Using shorthand:

const multiply = a => b => a * b;
console.log(multiply(4)(3)); // 12

The outer function takes in a and returns a function that takes in b which eventually returns the multiplication of a and b.

Currying is commonly associated with partial application. The idea is to create a function with two or more arguments, and we only know the value(s) for some of those arguments. We can use partial application (currying) to supply the knows values and get a function in return that works with unknowns (at the moment). Once the remaining arguments are known, we can execute the returned function.

I, in all honesty, have not used currying that much in real-life applications. There are other ways to accomplish what we are trying to do with currying (classes, callback functions and higher-order functions). It is good to know.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay