DEV Community

Prashanth Krishnamurthy
Prashanth Krishnamurthy

Posted on • Originally published at techformist.com on

1

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay