Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About the scope in javascript,why the following not output 21 but 22? [duplicate]

Tags:

javascript

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

Anyone knows the reason?

like image 488
asker Avatar asked Dec 28 '22 15:12

asker


1 Answers

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();
like image 58
user113716 Avatar answered Jan 04 '23 23:01

user113716