1

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 if I type code:

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

It doesn't return expected value 5. I don't even understand how sum(2)(3) calls function. Any explanation for this is very much appreciated.

4
  • Your function returns another function, and you then call that function.
    – SLaks
    Commented Feb 10, 2016 at 16:24
  • 5
    For further reading, the appropriate search term is "function currying" Commented Feb 10, 2016 at 16:25
  • @James Thorpe thank you, this is what I wanted Commented Feb 10, 2016 at 16:27
  • This link explains it also: javascript.info/tutorial/closures
    – Jose Luis
    Commented Feb 10, 2016 at 16:30

2 Answers 2

10

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.