DEV Community

Prashanth Krishnamurthy
Prashanth Krishnamurthy

Posted on • Originally published at techformist.com on

A simpler curry for Javascript

Here's a simpler way to do curry functions in Javascript.

We have previously seen currying in Javascript. A simple form and application of that concept is demonstrated below -

const addThem = add.curry(2);
const addTotal = addThem(1);
console.log("addTotal: ", addTotal); // 3

Enter fullscreen mode Exit fullscreen mode

Alternatively, we could avoid an external function or library and curry using bindings ..

function add(x) {
  return function(y) {
    return y + x;
  };
}

const addEm = add(1);

console.log(addEm(2)); // 3

Enter fullscreen mode Exit fullscreen mode

But, there is a simpler way to get the same result.

We just use arrow functions to collect arguments at different times.

const add = x => y => x + y;

const addEm = add(1);
console.log(addEm(2)); // 3

Enter fullscreen mode Exit fullscreen mode

We can make the code more readable with a different notation to do the actual curry -

const add = x => y => x + y;
console.log(add(1)(2)); // 3

Enter fullscreen mode Exit fullscreen mode

Of course, you have to rely back on the previously provided example if you don’t have all arguments in one go.

Top comments (0)