var x = 3;
(function (){
console.log('before', x);
var x = 7;
console.log('after', x);
return ;
})();
In the above code var X is initialized globally. So inside the function the first console.log should print “before 3” but i don’t get it. The reason is that i am trying to re-declare the global variable.
Can somebody explain why this is happening?
The JavaScript parser does Variable Hoisting when parsing your code. This means that any variable declaration will be moved to the top of the current scope, thus in your case, this code will get executed:
So your local variable
xgets declared at first with an initial value ofundefined.This should explain, why you get an “beforeundefined” for the first
console.log().