JavaScript Currying


Example

Currying is the transformation of a function of n arity or arguments into a sequence of n functions taking only one argument.

Use cases: When the values of some arguments are available before others, you can use currying to decompose a function into a series of functions that complete the work in stages, as each value arrives. This can be useful:

  • When the value of an argument almost never changes (e.g., a conversion factor), but you need to maintain the flexibility of setting that value (rather than hard-coding it as a constant).
  • When the result of a curried function is useful before the other curried functions have run.
  • To validate the arrival of the functions in a specific sequence.

For example, the volume of a rectangular prism can be explained by a function of three factors: length (l), width (w), and height (h):

var prism = function(l, w, h) {
    return l * w * h;
}

A curried version of this function would look like:

function prism(l) {
    return function(w) {
        return function(h) {
            return l * w * h;
        }
    }
}
6
// alternatively, with concise ECMAScript 6+ syntax:
var prism = l => w => h => l * w * h;

You can call these sequence of functions with prism(2)(3)(5), which should evaluate to 30.

Without some extra machinery (like with libraries), currying is of limited syntactical flexibility in JavaScript (ES 5/6) due to the lack of placeholder values; thus, while you can use var a = prism(2)(3) to create a partially applied function, you cannot use prism()(3)(5).