Variable shadowing and testing for existence before assignment in javascript
In the following code snippet I declare a global variable and then check for its presence inside a function.
    
    <script>
    x = 5;
    $(function() {
       var x = x || 3;
       console.log(x); // prints 3
    });
    </script>

This behaves differently: 

    <script>
    x = 5;
    $(function() {
       var y = x || 3;
       console.log(y); // prints 5
    });
    </script>

I expect that in the first example, the variable declaration in the inner scope will detect that x already exists in the global scope, and take its value. Why does the first example 3?

Specifically I recently wrote some code that checks `var _gaq = _gaq || []` in a jQuery ready scope and was confused when nothing was getting pubbed to Analytics.
Variable shadowing and testing for existence before assignment in javascript
===

In the following code snippet I declare a global variable and then check for its presence inside a function.
    
    <script>
    x = 5;
    $(function() {
       var x = x || 3;
       console.log(x); // prints 3
    });
    </script>

This behaves differently: 

    <script>
    x = 5;
    $(function() {
       var y = x || 3;
       console.log(y); // prints 5
    });
    </script>

I expect that in the first example, the variable declaration in the inner scope will detect that x already exists in the global scope, and take its value. Why does the first example 3?

Specifically I recently wrote some code that checks `var _gaq = _gaq || []` in a jQuery ready scope and was confused when nothing was getting pubbed to Analytics.