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:
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;
}
}
}
// 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)
.