Currying

suggest change

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).

Feedback about page:

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


Functions:
* Syntax
* Currying

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
25 Functions
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde