Function currying in JavaScript

November 12, 2014

Functional programming patterns are often more sensible when used with unary functions rather than JavaScript's standard multiple-argument functions.

Consider an addition function:

function add(x, y) {
  return x + y;
}
var z = add(20, 22); // 42

We can use add to write an increment function:

function increment(y) {
  return add(1, y);
}
var z = increment(41); // 42

But it would be cleaner if we didn't have to spend so much code writing a new function body for increment. To get there, let's revise our add implementation.

First, let's break add down into single-argument functions:

function add(x) {
  return function (y) {
    return x + y;
  }
}
var z = add(20)(22); // 42

Now we can implement increment by partially applying add with just a single argument:

var increment = add(1)
var z = increment(41); // 42

Writing all our functions as nested unary functions like this gets cumbersome, so we need a way to convert multiple-argument functions as needed. This is called currying, and can be done with a little helper function:

function curry(f, args) {
  var args = args || [];
  return function(x) {
    args.push(x);
    if (f.length == args.length) {
      return f.apply(null, args);
    } else {
      return curry(f, args);
    }
  };
}

Now we can use curry to curry arbitrary functions:

var increment = curry(add)(1);
var z = increment(41); // 42