Why is my global variable shadowed before the local declaration?

global-variables, javascript, variables

Solution

Due to hoisting, this is what gets executed:

x = 1; 
alert(x); 
var y = function() { 
    var x; // <-- this gets hoisted up from where it was.

    alert(x); 
    x = 2; 
    alert(x); 
} 
y();

At the start of function `y()`, the local variable `x` is declared but not initialized.

Problem

``` x = 1; alert(x); var y = function() { alert(x); var x = 2; alert(x); } y(); ``` The result of the 3 alerts is: `1`, `undefined`, `2` (Chrome 25) My question is: why the second alert is undefined? Why not 1? Isn't there a global variable x?

Original source