function createCounter() {
let counter = 0;
console.log(
'counter='+counter+' >new createCounter() call>new closure'
);
const myFunction = function() {
counter = counter + 1;
console.log(counter + ' aha! In closure');
return counter;
}
return myFunction;
}
const increment = createCounter();
//console.log(counter);
const c1 = increment();
const c2 = increment();
//console.log(counter);
const c3 = increment();
if (counter = 3) {console.log('This means I see the closure value?maybe')}
else {console.log('Nada!')}
console.log(counter);
When I run the above code if I try to console.log(counter) it throws an exception error as expected. But when I try the if statement it can âaccessâ counter, and then afterwards I can console.log(counter), change counter, etcâŚ
Google hasnât helped much so farâŚ