DEV Community

artemismars
artemismars

Posted on • Edited on

What is Currying in javascript

Description

Currying: n parameters can turn into n functions.

Example code

n parameters

function foo(x, y, z) {
  return x + y + z;
}
Enter fullscreen mode Exit fullscreen mode

n functions

function foo(x) {
  return function bar(y) {
    return function baz(z) {
      return x + y+ z;
    }
  }
}

const result = foo(10)(10)(10);
console.log(result);

>> 30
Enter fullscreen mode Exit fullscreen mode

This is possible because functions are First Class Citizens in javascript.

When do we use currying?

If n parameters are passed into one function then the function does complex operation inside itself then it will be very difficult to track how the function is working with each parameter.
But if you use currying then you can split how each step of the operation works parameter by parameter.

Top comments (0)