Help understanding how "if statement" made closure variable global?

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…

The if statement is assigning counter inside the if expression: counter = 3. That sets its value to 3 and makes it available for the console.log command that follows. Normally, though, you would compare in an if, not assign: counter == 3 or counter === 3. In this case you’d still get an error because counter hadn’t been declared or defined yet. Using just = will define.

1 Like

Thank you! It’s like I declared a new variable b/c I used the “=” operator…seems obvious now. VS code debugger throws error as I was expecting with “===”.
Again Thanks!
if (typeof counter !== ‘undefined’) does the trick!