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.
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.
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.