In JavaScript, Variable Initialization always takes precedence. Even, Function objects are created for all Function Declarations and got assigned to Global Objects. For ex. look at the following code:
var x = 500;
function check() {
if (typeof(x) === 'undefined') {
var x = 100;
alert(x);
}
alert(x);
}
check();
alert(x);
The above code will give 3 alert messages with the response as 100, 100, & 500
Explanation
Actually, this is how the code is getting compiled.
/* x is already defined and assigned with value 5 and is available in
the Global scope. */
var x=500;
function check( ) {
// variable x get hoisted to the top.
var x;
if (typeof(x) === 'undefined') {
//therefore, here it will be undefined.
//assigning value 100
x = 100;
//x will be 100
alert(x);
}
// x will be 100 , value of x will be 100 inside the function scope.
alert(x);
}
check();
/* here the value of x will be still 500. Since it has its own value available in
the global scope.*/
alert(x);
As you can see, x has both a Global as well as a local declaration. Now even though the local variable x is declared inside the if loop, at the time of execution, when the method check is called, first all the variables of that function (in this case only x) gets declared. So x is declared (not defined) even before the if loop, & when the condition matches, 100 is then assigned to the local variable x. However, the scope of this 100 lies within the function only and so, when an alert is raised in the last line, it will display 500 (Value of the Globally declared variable x).