4
function t()
{
    var x = 1;
    if(true)
    {
        var x = 2;
        alert(x);
    }
    alert(x);
}
t();

Anyone knows the reason?

asker
  • 2,159
  • 3
  • 22
  • 27

3 Answers3

6

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();
user113716
  • 318,772
  • 63
  • 451
  • 440
  • Not a very optimistic "yet". I doubt this will ever change. Imagine the nightmare of breaking decades(?) of code. EDIT: I stand corrected, your edited link provides some additional insight I did not consider. – anthony sottile Aug 17 '11 at 01:41
  • 1
    @Anthony: If your code is running in the browser, then very true. Out of the browser in free-standing JS engines, there's reason to be optimistic (or even to enjoy it today). :o) – user113716 Aug 17 '11 at 01:44
3

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();
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
1

Variables in Javascript are scoped to the function, not to blocks. You've got two vars, but there's really only one x.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662