ES6 Currying

Learn about ES6 currying which is often used in JS libraries like Redux.

·

1 min read

ES6 Currying

Observe the code below:

const sum = a => b => a + b;

Let's try to understand the above code.

In the above code snippet, there are two function, sum and the anonymous function returned by sum. The sum takes one argument and the anonymous function returned by sum requires one argument.

To understand the above function better lets call it.

const sum = a => b => a + b;
console.log(sum(2)(3));

The console output of the above snippet will be 5. The sum function took 2 as an argument and returned an anonymous function. The function returned by sum(2) can be written as:

/* pseudocode just for the sake of understanding */
sum(2) returns b => 2 + b;

Next, the anon is passed with argument 3, and it returns sum of 2+b that is 2+3. And finally the result is shown on the console.

So, the above curried arrow function code can also be written as:

const sum = function(a) {
    return function(b) {
        return a + b;
    }
}

console.log(sum(2)(3));

Reference: Codekirei