DEV Community

Cover image for What is Currying in JavaScript?
Rahul
Rahul

Posted on • Originally published at rahulism.tech

9 3

What is Currying in JavaScript?

Currying is a technique of evaluating function with multiple arguments, into sequence of function with single argument.

Currying is a transformation of function that translates a function from callable as f(a, b, c) into callable as f(a)(b)(c).

function curry(f) {
    return function(a) {
        return function(b) {
            return f(a,b); 
        }; 
    }; 
}
function sum(a, b) {
    return a + b; 
}
 let curriedSum = curry(sum); 
 curriedSum(1)(2); 

 // 3
Enter fullscreen mode Exit fullscreen mode

Why is it Useful?

  • Currying helps you to avoid passing the same variable again and again.
  • Little pieces can be configured and reused with ease.

How to convert an existing function to curried version?

The curry function does not exist in native JavaScript. But libraries like lodash makes it easier to convert a function to curried one.

let add = function(a, b, c) {
    return a+ b + c; 
}; 
let curried = _.curry(add); 
let addByTwo = curried(2); 

console.log(addByTwo(0, 0)); //2
console.log(add(2, 1, 1)); // 4
console.log(curried(4)(5)(6)); // 15
Enter fullscreen mode Exit fullscreen mode

🚀Thanks For Reading | Happy Coding🏗

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

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

Okay