DEV Community

 Bishnu Prasad Chowdhury
Bishnu Prasad Chowdhury

Posted on

Currying in JavaScript

In JavaScript a function with multiple arguments can be broken into a series of interconnected functions where each function returns a new arrow function that accepts a single argument. It goes on until the arguments are finished so a 3 argument function can have a function inside it returning another function taking up one argument each.

Currying can be achieved with only those function that accepts multiple argument else not.

A normal function would look like below

function sum(x,y,z){
  return x+y+z;
}

sum(2,3,4)
>9

Enter fullscreen mode Exit fullscreen mode

Now let's see how the same function would look like while curried

function sum(x){
  return (y) => {
    return (z) => {
      return x+y+z;
    }
  }
}

sum(2)(3)(4)
> 9
Enter fullscreen mode Exit fullscreen mode

The last function that is returned has access to the outer function scope (closure feature) hence it can easily get the values of x and y and return the sum with z.

Currying is useful in those scenarios where a function accepts multiple arguments where one or two argument are constant on every function call i.e their value stays the same. In that scenario we can use currying and reduce the effort of passing the constant argument in each function call.

Suppose a function fx is having a formula x + y + z + c where c is constant say €25 for every function call but the other values changes everytime. Then we can write like below:

function fx(x){
  return (y) => {
    return (z) => {
      return (c) => {
        return x+y+z+c;
      }
    }
  }
}

const simplifyFX = fx(25);
simplifyFX(1)(2)(3)
>31

Enter fullscreen mode Exit fullscreen mode

We can use lodash library to curry function on the fly.

var a = function (x,y,z){
  return x+y*z;
}

var curryMe = _.curry(a);
var net =  curryMe(5);

net(2,3);
>11
net(2)(2);
>9
net(2,3,4)
>11
Enter fullscreen mode Exit fullscreen mode

We can also achieve currying using bind on the above function.

var net2 = a.bind(this, 5)
net2(2,3)
>11
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
sznroe profile image
Sujan Rai

It was new to me. Thanks!