I've been trying to understand how closures in JavaScript work, but I've been having some problems understanding some parts of it.
Let's see this example:
const Component = () => {
let counter = 0;
const logger = () => {
console.log(counter);
}
setTimeout(() => counter = counter + 10, 1000);
return logger;
}
const myLogger = Component();
myLogger(); // output after ~1s: 10
When a "closure" is created, the variables that the logger
function references (which are not part of the function, and in this case: counter
), are stored in the function's hidden [[Scope]]
property, so that the function can reference them when it is executed.
I thought that the [[Scope]]
property had a copy of the initial values that the function references because it is a lexical scope. But after executing my code, I realized that the value of counter
changes way after the function is created. I thought that the value of counter
should be 0
after calling myLogger()
, because it is the initial value that is stored in the function's scope and can only be changed from within the function.
The setTimeout
operation shouldn't increase the counter
that is inside of logger
. Or at least that's what I thought.
Did I get something wrong or am I missing something else?