DEV Community

artemismars
artemismars

Posted on • Edited on

2 1

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)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

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

Okay