Seeking clarification on the concept of functions in functions and scoping. I am currently delving into the realm of functions and variable scope and stumbled upon a tutorial that was quite helpful, but I find this particular aspect confusing.
The Challenge:
Develop a function called sum that behaves as follows: sum(a)(b) = a+b
and can accept any number of brackets. Here are some examples:
sum(1)(2) == 3
sum(5)(-1)(2) == 6
The Solution:
function sum(a) {
var sum = a;
function f(b){
sum += b;
return f;
}
f.toString = function() { return sum };
return f; //line 12
}
alert( sum(1)(2) ); // 3e
The Explanation:
In order for sum(1)
to be callable as sum(1)(2)
, it needs to return a function.
This function can either be invoked or converted to a number using valueOf
.
The solution provided is quite straightforward:
My Interpretation:
The f
in function f(b)
refers back to the scope defined from lines 02 to 12.
The f
in f.toString
represents the current returned f
from function(b)
.
The subsequent return f
goes back to the outer scope outside the sum(a)
function.
Issue:
I'm struggling to identify where my thought process may need adjustment, since as I mentioned earlier, it seems like the function wouldn't be called again. Where in the code does it allow for the 'multiple parentheses' functionality?
Additionally, have I correctly identified where the f
s are being returned? It would be greatly appreciated if someone could offer some insights.