So we have this code, found at this page, which I am using to try to understand variable scopes, IIFEs, and so:
// Because this function returns another function that has access to the
// "private" var i, the returned function is, effectively, "privileged."
function makeCounter() {
// `i` is only accessible inside `makeCounter`.
var i = 0;
return function() {
console.log( ++i );
};
}
// Note that `counter` and `counter2` each have their own scoped `i`.
var counter = makeCounter();
counter(); // logs: 1
counter(); // logs: 2
var counter2 = makeCounter();
counter2(); // logs: 1
counter2(); // logs: 2
i; // ReferenceError: i is not defined (it only exists inside makeCounter)
This way produces a similar result as using a global variable and using it on each function calling, in a more safe, elegant way, isn´t it?
2 questions
1-I can´t see how the i variable scope works to maintain the counter value and not to reset it to 0 each time function is invoked again. I know this is used to avoid global variables but I can´t see how it is done to maintain the counter value between different calls to
counter();
2-why the funcion returned shows console.log(value) only when you have assigned the function to another variable?
var counter2 = makeCounter();
counter2(); // logs: 1
But
makeCounter(); //logs nothing
I don´t know why. Ok, I guess on
makeCounter();
you are only declaring the returning function, not calling it... But I don´t know why is different when I do
var counter2 = makeCounter();
counter2();