Currying

suggest change

Currying turns a function of n arguments into a sequence of n functions that each take 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):

const 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:

const prism = l => w => h => l * w * h;

Call that sequence with prism(2)(3)(5), which evaluates to 30.

JavaScript has no placeholder arguments, so you cannot skip a parameter. prism()(3)(5) does run: l is undefined, and the product is NaN. const area = prism(2)(3) is a partially applied function that still expects the height.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents