Additional Blogs by SAP
Showing results for 
Search instead for 
Did you mean: 
0 Kudos

There is a piece of JavaScript codes below:

const add = x => y => x + y
var c = add(1)(2);

When executed, c is equal to 3 in the runtime. Why?

Let's debug in Chrome.

1. Only one argument, 1. Pay attention to the highlight part in line 19. It means argument x is set to 1.

Check in console, x = 1, y is not available at this time.

And here below gives us a hint that add(1)(2) will first bind x to 1, and return a new function f(y) = x + y = 1 + y.

2. when clicking step into again, pay attention to the highlight part in line 21. It means now the function f(y) = 1 + y is executed, and this time, the argument y, is set as 2.

And the argument x's value 1 is still preserved in the context via Closure.

So finally we get 3 as result. So const add = x => y => x + y just creates a curried function which has exactly the same function as below:

function add(x){
  return function(y){
  return x + y