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

Anyone knows the reason?

1
  • 4
    welcome to javascript :) Commented Aug 17, 2011 at 1:47

3 Answers 3

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();
Sign up to request clarification or add additional context in comments.

2 Comments

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: 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)
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();

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.