Hope somebody finds the time to explain little about functions in functions and scoping. I am trying to understand little more on functions and scope of variables and found a qu
The function sum
returns a function, which we refer to as f
.
The function f
also returns a function: in fact, the function f
returns itself.
When the function f
is defined inside of sum
, it gets permanent access to all variables currently visible in the scope chain. Here, it includes the locally-defined variable sum
(the local running sum tally) and f
(the function itself). (A "closure" is what we call the functional code of f
along with all its in-scope variables.)
Because f
returns itself, you can chain f
with repeated calls:
var this_is_f = sum(1);
var same_f_again = this_is_f(2);
var f_a_third_time = same_f_again(3);
Or simply:
sum(1)(2)(3);
It is important to note that in my first example, I don't create new functions; instead, I just refer to the exact same function object with three different identifiers.
Each call to sum
creates a brand-new f
with a new local sum
in its scope (here, I mean the local sum
defined on the first line of the function named sum
). However, calling the function sum
does not clobber any old f
, because each call to sum
instantiates a new f
(and knows nothing about any other f
s that have been created on prior calls to sum
). That way, you can have multiple tallies running:
var first_tally = sum(1)(2); // first: 3
var second tally = sum(4)(5); // second: 9
first_tally(3); // first: 6
second_tally(6); // second: 15
The reason you're able to see a meaningful result at any time is that f
stingifies to the value of sum
, instead of showing you its source code.