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

**URL:** <https://forum.kirupa.com/t/help-understanding-how-if-statement-made-closure-variable-global/641096>\
**Category:** programming\
**Created:** [November 16, 2019, 11:16pm UTC](https://forum.kirupa.com/t/help-understanding-how-if-statement-made-closure-variable-global/641096 "2019-11-16T23:16:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![drcberry](https://avatars.discourse-cdn.com/v4/letter/d/e19adc/32.png) [@drcberry](https://forum.kirupa.com/u/drcberry)\
**Post date:** [November 16, 2019, 11:16pm UTC](https://forum.kirupa.com/t/help-understanding-how-if-statement-made-closure-variable-global/641096/1 "2019-11-16T23:16:28Z")

</div>

```
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…

---

<div class="post-metadata">

**Author:** ![senocular](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/senocular/32/7217_2.png) [@senocular](https://forum.kirupa.com/u/senocular)\
**Post date:** [November 17, 2019, 12:49am UTC](https://forum.kirupa.com/t/help-understanding-how-if-statement-made-closure-variable-global/641096/2 "2019-11-17T00:49:23Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![drcberry](https://avatars.discourse-cdn.com/v4/letter/d/e19adc/32.png) [@drcberry](https://forum.kirupa.com/u/drcberry)\
**Post date:** [November 17, 2019, 12:56am UTC](https://forum.kirupa.com/t/help-understanding-how-if-statement-made-closure-variable-global/641096/3 "2019-11-17T00:56:41Z")

</div>

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!
