Back to the lesson

Are counters independent?

importance: 5

Here we make two counters: counter and counter2 using the same makeCounter function.

Are they independent? What is the second counter going to show? 0,1 or 2,3 or something else?

function makeCounter() {
  let count = 0;

  return function() {
    return count++;
  };
}

let counter = makeCounter();
let counter2 = makeCounter();

alert( counter() ); // 0
alert( counter() ); // 1

alert( counter2() ); // ?
alert( counter2() ); // ?

The answer: 0,1.

Functions counter and counter2 are created by different invocations of makeCounter.

So they have independent outer Lexical Environments, each one has it’s own count.