I have two counter realizations seems identical (for me), here is my code:
var fakeCounter = function() {
var i = 0;
return function() {
return i++;
}
};
// And
var counter = (function() {
var i = 0;
return function() {
return i++;
}
}());
// And here the confusion:
console.log(fakeCounter()()); // 0
console.log(fakeCounter()()); // 0
console.log(fakeCounter()()); // 0
console.log(counter()); // 0
console.log(counter()); // 1
console.log(counter()); // 2
So, the first counter doesn't work, while the second does. And I can't get why, because counter()
is equal to fakeCounter()()
on my mind.
Can someone clarify that?