function t()
{
var x = 1;
if(true)
{
var x = 2;
alert(x);
}
alert(x);
}
t();
Anyone knows the reason?
Because JavaScript (well ECMAScript) does not have block scope (yet). Just function scope.
There's really just one variable declaration that is hoisted to the top of the function, so x=2
is overwriting the initial value of 1
.
function t()
{
var x = 1;
// v---------immediately invoked function to create a new scope
(function() {
// new variable scope
if(true)
{
var x = 2;
alert(x); // 2
}
})();
alert(x); // 1
}
t();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With