What is currying?

Currying transforms a function with multiple arguments into a sequence/series of functions each taking a single argument.

So a function like func(a,b,d) can be transformed into func(a)(b)(d).

Currying takes advantage of closures by creating functions that return other functions. Because these functions have persistent memories, we are able to access variables “outside” of nested functions.

Let's look at the example below.

function curry(f) {
return function (a) {
return function (b) {
return f(a, b);
};
};
}
function sum(a, b) {
return a + b;
}
let curriedSum = curry(sum);
console.log(curriedSum(1)(2)); // 3
let addOne = curriedSum(1);
console.log(addOne(2)); // 3
view raw currying_1.js hosted with ❤ by GitHub

In the above example, we have defined a curry function whose parameter is a function. And inside of the curry function, we have 2 nested anonymous functions each taking a unique parameter. The inner most function, will have access to all variables in the parent and grandparent scope and because of this, will return the passed in function from curry.

Because of this set up, we have some ways of using this logic. On line 15, we create a variable that is the result of passing the sum function to curry. And then on line 16, we now have a couple of arguments, 1 and 2, that will lead to the result of 3.

On line 18, we create the variable addOne as a result of passing a single argument to the curried function. This allows us to use this function anytime we want to simply add 1 to any number, thus making our code reusable.

function curry(func) {
return (a) => (b) => func(a, b);
}
function sum(a, b) {
return a + b;
}
const curriedsum = curry(sum);
console.log(curriedsum(2)(3)); // 5
view raw currying_2.js hosted with ❤ by GitHub

In this example, we are simply re-writing the first example to show another way to re-writing the curry function.