Suppose we defined this function in a global scope:
function createCounter() { var counter = 0; function increment() { counter = counter + 1; console.log("Number of events: " + counter); } return increment; }
In most examples explaining closure, I see execution:
createCounter();
from a global scope will simply return an internal function:
function increment() { counter = counter + 1; console.log("Number of events: " + counter); }
Now this makes full sense because of this line in the createCounter function declaration
return increment;
So my question is: why is this:
var counter1 = createCounter(); counter1(); Number of events: 1
Finally, for the function to work?
Essentially not counter1 and createCounter both pointers to this internal function that exist in the global scope?
Maybe the best way to ask this is why counter1() works, and not just return an internal function like createCounter ?
source share