Why is my global variable obscured before the local declaration?

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

Score three warnings: 1, undefined, 2(Chrome 25)

My question is: why is the second warning undefined? Why not 1? Is there a global variable x?

+5
source share
3 answers

Thanks to hoisting , this is what is done:

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 beginning of a function, a y()local variable is xdeclared, but not initialized.

+12
source

A variable declaration in a function goes up. So it technically looks like this:

var y = function() {
    var x;

    alert(x);

    x = 2;
};

A local variable eclipses a global one. This is why the warning returns undefined.

+1
source

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

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

So, x in the second warning is "undefined", not "1". Therefore, when you declare a variable in a function, I recommend that you declare variables at the top of your function.

0
source

All Articles