Currying in Javascript
Currying is a technique of working with functions. Currying can make a function callable from f(a, b, c)
to f(a)(b)(c)
A simple example
1
2
3
4
5
6
7
// example 1 - sum(a, b)
function sum(a, b) {
return a + b;
}
const val = sum(1, 2);
console.log(val); // 3
1
2
3
4
5
6
7
8
9
// example 2 - sum(a)(b)
function sum(a) {
return function(b) {
return a + b;
}
}
const val = sum(1)(2);
console.log(val); // 3
On line 2 in example 2, we have transformed the sum
function into curry
function.
- When it first called as
sum(1)
on line 8, theargument
passed to it will get saved in the Lexical Environment, and a new wrapper is returnedfunction(b)
. - Then this wrapper is called with
2
as anargument
, and it passes the call to the originalsum
. As the previous value was saved in the Lexical Environment, it will be available andreturn 3
as an output.
More advanced example
1
2
3
4
5
6
7
8
9
10
function add(a) {
return function(b) {
if (b) {
return add(a + b)
}
return a
}
}
console.log(add(10)(1)()); // 11