0

Going through some lessons about lexical environment, closure, and that function are objects. But, the following code, I can't understand how counter.count can accumulate, even when it gets reset back to 0 every call at counter.count = 0

Function properties can replace closures sometimes. For instance, we can rewrite the counter function example from the chapter Variable scope to use a function property:

Excerpt from Javascript.info

function makeCounter() {
  // instead of:
  // let count = 0

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

  counter.count = 0;

  return counter;
}

let counter = makeCounter();
alert( counter() ); // 0
alert( counter() ); // 1

even in this example without using properties

function makeCounter() {
  let count = 0;

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

let counter = makeCounter();
alert( counter()); //0
alert( counter()); //1

does let declare count once during function declaration? Subsequent repeated calls in counter() wouldn't trigger let counter = 0; again?

wouldn't repeated calls be equalvent like the follow code? b/c I know this will give an error

let counter = 0;
let counter = 0;

code excerpt from Javascript.info

Barmar
  • 741,623
  • 53
  • 500
  • 612
Brandon
  • 377
  • 3
  • 11
  • 1
    _"wouldn't trigger let counter = 0; again?"_ - No. `makeCounter` returns `function counter() { ... }`. And `counter()` only reads and adds to `count` – Andreas Jan 20 '20 at 18:05
  • 1
    [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Andreas Jan 20 '20 at 18:06

1 Answers1

2

let counter = 0 only happens when you call makeCounter(). Each call to that returns a different closure, which has its own instance of the count variable.

Calling counter() doesn't call makeCounter() again, so it doesn't create a new counter variable. The closure remembers the instance of count that was created when you first called makeClosure().

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks, I got confused thinking assignment copied the entire code from makeCounter. Which is not the case because we ran makeCounter() during assignment, so only the return value is given to counter() ... basically ```counter.count++``` or ```return count++;``` – Brandon Jan 20 '20 at 18:15