· 1 min read Comments

What is Currying in JavaScript? Advantags of using currying

  1. Calligraphy Authors's Headshot
    Rahulism

    Owner


Table Of Contents


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

Curyying 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

Why is it Useful?

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

🚀 Thanks For Reading | Happy Coding


Share on:
Ashish Lahoti avatar
About Rahulism
I’m a front-end Developer and Blogger. Focused more on User Experience. I’m Passionate about startups