Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 986
Albert Gao Avatar asked Apr 02 '13 13:04

Albert Gao


2 Answers

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.

like image 108
Ja͢ck Avatar answered Sep 23 '22 22:09

Ja͢ck


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.

like image 31
David G Avatar answered Sep 20 '22 22:09

David G