This page looks best with JavaScript enabled

A simpler curry for Javascript

 ·   ·  ☕ 1 min read

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 -

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

Or, we could avoid a external function or library and curry using bindings ..

1
2
3
4
5
6
7
8
9
function add(x) {
  return function(y) {
    return y + x;
  };
}

const addEm = add(1);

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

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

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

1
2
3
4
const add = x => y => x + y;

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

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

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

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

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things


What's on this Page