'Why is my global variable shadowed before the local declaration?

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?



Solution 1:[1]

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.

Solution 2:[2]

The variable declaration in the function is hoisted to the top. So it technically looks like this:

var y = function() {
    var x;

    alert(x);

    x = 2;
};

The local variable overshadows the global one. That is why the alert returns undefined.

Solution 3:[3]

Since scope in JavaScript is a function object. When you execute some code in a function(your code sample), "alert(x)" will find if there's any definition of "x" in the function. So, there's a "var x = 2" in this function. But the JavaScript runtime will explain your code like this:

x = 1; 
alert(x); 
var y = function() { 
  var x;
  alert(x); 
  x = 2; 
  alert(x); 
} 
y(); 

So, the x in the second alert is "undefined" not "1". So when you declare some variable in a function, I recommend you to declare the variables in the top of your function.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 KiddKai