When working with es6 js, you’ll see arrow functions like this:
1 |
let add = x => (y) => x + y; |
Let’s break it down and see what’s happening.
Let’s process from left to right.
We first have a temp variable add that takes on a function with parameter x and a return expression.
1 2 3 |
let add = function(x) { return <some expression> } |
Then we see that the return expression is (y) => x + y, which is a function.
Hence, this usage is a curry function. We return a partial function for continual external use.
In our curry function, the y is a parameter.
1 2 3 |
function (y) { return x + y; } |
Hence, we we combine the two, we get:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
console.log(`------ es5 way ------`); let add = function(x) { // currying, using partial function return function(y) { // x is accessed in the inner function via closure return x + y; } } let sixPlus = add(6); console.log(sixPlus(5)); console.log(sixPlus(8)); console.log(sixPlus(4)); console.log(add(5)(4)); console.log(add(8)(8)); |
The es6 way:
1 2 3 4 5 6 7 8 9 10 11 12 |
console.log(`------ es6 way ------`); let add2 = x => (y) => x + y; let eightPlus = add2(8); console.log(eightPlus(8)); console.log(eightPlus(10)); console.log(eightPlus(1)); console.log(add2(4)(6)); console.log(add2(1)(1)); console.log(add2(0)(0)); |