Search code examples
javascripthoisting

JavaScript Global Var Hoisting Issue


Here is my basic issue...

<script>
    var window.my_Global = false;
</script>

<script>
    if(my_Global){...} //my_Global here is undefined, not false??
</script>

I know there must be a simple solution but I'm pretty stuck...


Solution

  • Remove var:

    window.my_Global = false;
    

    You don't need the var statement to set properties of an object. In fact, that's invalid syntax:

    <script>
        window.my_Global = true;
    </script>
    
    <script>
        console.log(my_Global);
        if(my_Global){
            alert("Hello world!");
        }
    </script>