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