Implement Currying | JavaScript Interview Questions
@Yomesh Gupta

JavaScriptIntermediate
729
Do you see value in our efforts?

Devtools Tech is a free platform for Frontend Engineers. It takes a lot of time, effort, and finanical resources to keep the platform running. If you see any value in our work and would like to support us then you can do using the following options.

InternationalDomestic

The concept of currying happens when a function does not accept all of its arguments up front. Instead it takes the first argument and returns another function. The returned function is supposed to be called with the second argument, which in turn again returns another function. And this continues till all the arguments have been provided. And then the function at the end of the chain will be the one that returns the value that we want.

const add = (a, b, c, ..., n) => {
    return a + b + c + ... + n;
};

const curriedAdd = curry(add);

curriedAdd(1,2,3,4,5); // returns 15;
curriedAdd(1)(2,3,4,5); // returns 15;
curriedAdd(1,2)(3,4,5); // returns 15;
curriedAdd(1,2,3,4)(5); // returns 15;

Points to Remember

  • Input function to curry can take n arguments.
  • curriedAdd should return the final output when received arguments matches the original add function arguments length.

Loading IDE...