Hey everyone, just had a quick question about the closure example given in Novice to Ninja Chapter 11 the Closure example. Just having trouble wrapping my head around this one, was hoping someone could explain why this occurs.
The example given is this:
function counter(start) {
i = start;
return function () {
return i++;
}
}
var count = counter(1);
count();
<< 1
count();
<< 2
My question here is that when you call count() the first time, why is it returning a 1, when the function inside of it, is telling it to increase itself by one. So shouldn’t the first output be 2 instead of 1, I did this in the browser as well to test it out and it came out with the same result as the book, so what I am asking is why does it return 1 the first time if the function is asking it to increment itself by 1, so thus, shouldn’t it be 2? Thank you for the help.