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.

/wp-content/uploads/2015/12/clipboard1_854423.png


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

/wp-content/uploads/2015/12/clipboard2_854424.png

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.

/wp-content/uploads/2015/12/clipboard3_854425.png

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.

/wp-content/uploads/2015/12/clipboard4_854429.png

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

/wp-content/uploads/2015/12/clipboard5_854430.png

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
  }

}

To report this post you need to login first.

Be the first to leave a comment

You must be Logged on to comment or reply to a post.

Leave a Reply