[removed]What is meaning of sum(2)(3) //returns 5;

后端 未结 2 1085
感动是毒
感动是毒 2021-01-07 09:58

Here is code blow to return it\'s value.

function sum(a){
  return function(b){
    return a+b;
  }
}
sum(2)(3);

It returns 5 but

相关标签:
2条回答
  • 2021-01-07 10:18

    Your 'sum' function returns another function which returns a+b (2 parameters). Both functions together require two parameters: (a) and (b)
    The inner most return, returns a+b. Plugging in your parameters, we get the equation: 2+3.
    Which gives you 5.

    Please let me know if you have any questions or concerns.

    0 讨论(0)
  • 2021-01-07 10:19

    This is called a closure.

    sum(a) returns a function that takes one parameter, b, and adds it to a. Think of it like this:

       sum(2)(3);
    
       // Is equivalent to...
       function add(b){
           return 2+b;
       }
       add(3);
    
       // Which becomes...
       return 2+3; // 5
    

    Your second snippet doesn't work because you're trying to reference b from the outer function, but only the inner function has any notion of what b is. You want to change this:

    function sum(a){
      function add(b){
        return a+b;
      }
      return add(b);
    }
    

    To this:

    function sum(a){
      function add(b){
        return a+b;
      }
      return add; // Return the function itself, not its return value.
    }
    

    Which is, of course, equivalent to the first snippet.

    0 讨论(0)
提交回复
热议问题