patternjavascriptCritical
What is 'Currying'?
Viewed 0 times
curryingwhatstackoverflow
Problem
I've seen references to curried functions in several articles and blogs but I can't find a good explanation (or at least one that makes sense!)
Solution
Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument. Here's an example in JavaScript:
This is a function that takes two arguments,
This is a function that takes one argument,
function add (a, b) {
return a + b;
}
add(3, 4); // returns 7
This is a function that takes two arguments,
a and b, and returns their sum. We will now curry this function:function add (a) {
return function (b) {
return a + b;
}
}
This is a function that takes one argument,
a, and returns a function that takes another argument, b, and that function returns their sum.add(3)(4); // returns 7
var add3 = add(3); // returns a function
add3(4); // returns 7
- The first statement returns
7, like theadd(3, 4)statement.
- The second statement defines a new function called
add3that will add3to its argument. This is what some may call a closure.
- The third statement uses the
add3operation to add3to4, again producing 7 as a result.
Context
Stack Overflow Q#36314, score: 1122
Revisions (0)
No revisions yet.