This page looks best with JavaScript enabled

Currying in Javascript

 ·   ·  ☕ 2 min read

Currying is a technique of splitting functions with one or more arguments into a sequence of functions that are invokable with predefined arguments. In other words, you can split fn (a,b,c) into fn(a)(b)(c).

That was not quite helpful - let us see an example.

1
2
3
4
5
6
let getSquared = (x, y) => {
  return x * y;
};
let getSquared = getProduct.curry(2);

console.log(getDouble(3)); // 9

Before you rush to your editor to introduce this in your project know this - it may not work as-is in your JS installation. Either you need to install a package that supports currying or write one yourself.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Function.prototype.curry = function() {
  if (arguments.length < 1) return this;

  return () => {
    return this.apply(this, [...arguments].concat([...arguments]));
  };
};

let getProduct = function(x, y) {
  return x * y;
};
let getSquared = getProduct.curry(3); // 9

console.log("getSquared ", getSquared(10));

Currying is more widely used in functional programming - ergo, no one needs to blame anyone that they have not come across it for so long.

I have tried to curry a few functions in real-world applications and have failed rather spectacularly. I catch myself going back the traditional way one too many times when I hit bugs that are difficult to fix.

But, there is indeed a lot of hype to use curry complementing (or replacing?) our favourite classes. Let’s see how this holds itself in the future.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things