I feel as though my knowledge with closures is almost there, but I’m struggling to grasp exactly why this first code snippet logs 0 (is a stale closure) however, the second code snippet works and logs the updated value ..
Is this some kind of reference issue?
In the first example, are we not tracking the reference of count and only assigning its initial value to message?
By moving the message variable inside of the log function are we somehow telling JS to track the reference of the count value?
function createIncrement() {
let count = 0;
function increment() {
count++;
}
let message = count;
function log() {
console.log(message);
}
return [increment, log];
}
const [increment, log] = createIncrement();
increment();
log();
// this will log 0
function createIncrement() {
let count = 0;
function increment() {
count++;
}
function log() {
let message = count;
console.log(message);
}
return [increment, log];
}
const [increment, log] = createIncrement();
increment();
log();
// this will log 1





