function t()
{
var x = 1;
if(true)
{
var x = 2;
alert(x);
}
alert(x);
}
t();
Anyone knows the reason?
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();
The 'var' keyword applies within a whole function, so the code you have will behave identically to this:
function t() {
var x = 1;
if (true) {
x = 2;
alert(x);
}
alert(x);
}
t();
Variables in Javascript are scoped to the function, not to blocks. You've got two var
s, but there's really only one x
.