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.

  1. When it first called as sum(1) on line 8, the argument passed to it will get saved in the Lexical Environment, and a new wrapper is returned function(b).
  2. Then this wrapper is called with 2 as an argument, and it passes the call to the original sum. As the previous value was saved in the Lexical Environment, it will be available and return 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