-1

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?

Cid
  • 14,968
  • 4
  • 30
  • 45
kexek
  • 29
  • 9

1 Answers1

-1

You are both, correct and wrong, at the same time: fakeCounter()() and counter() are the same, but only when invoked once:

  • How they are alike:
    • fakeCounter() creates a function with a closure, as does the IIFE for the var counter.
    • The next () invokes that function.
  • How they are different:
    • fakeCounter() creates a new function every time, that captures its own var i inside it.
    • The IIFE is only invoked once, so there exists only one var i.

I encourage you to play around with this bit of code:

let a = fakeCounter();   // a is a counter
let b = fakeCounter();   // as is b
// ... but are they the same? Hmmmm...
console.log(a === b);   // false  -- Nope, they are separate functions

console.log(a());         // 0
console.log(a());         // 1
console.log(a());         // 2

console.log(b());         // 0
console.log(b());         // 1
console.log(b());         // 2

console.log(counter());   // 0
console.log(counter());   // 1
console.log(counter());   // 2
djlauk
  • 3,359
  • 1
  • 12
  • 12