search

Home  >  Q&A  >  body text

javascript - Why does the following code output "undefined"?

code show as below:

if(!("a" in window)){
    var a = 1;
}
alert(a);

I have read the relevant explanation. The reason is that variable declaration will be promoted, but variable assignment will not be promoted, but I still don’t understand it. Has the code in the if statement block been executed? If not, which statement caused the variable to be promoted? If executed, the value of a should be 1.
Tried to enter the following code into the console

alert(b)//报错,b未被定义;
if (2>1){
    var b=1;
}
alert(b)//1
迷茫迷茫2779 days ago776

reply all(6)I'll reply

  • 巴扎黑

    巴扎黑2017-06-12 09:32:20

    if("a" in window)
    var a = 1;
    alert(a);

    reply
    0
  • PHP中文网

    PHP中文网2017-06-12 09:32:20

    if(!("a" in window)){
        var a = 1;
    }
    alert(a);

    Question 1

    Not executed

    Question 2

    Variable promotion is not caused by statements, but is actually done when the js engine compiles your js code!

    What’s the principle?

    Take chrome as an example. When the first v8 engine encounters your code, it will become like this:

    var a;
    if(!("a" in window)){
        a = 1;
    }
    alert(a);

    Then because a has been declared, !("a" in window) is always false! The statement inside if is not executed!
    So when alert(a), a has no value

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-12 09:32:20

    I used your code and the result was popup 1

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-12 09:32:20

    The variable declaration becomes the following code after promotion

    var a; // 这里变量声明提升了
    if(!("a" in window)){
        a = 1;
    }
    alert(a);

    After the variable declaration is upgraded, a is defined first, and then the if statement is entered. a is a property of window. After being inverted, it becomes false, so the code in the if statement is not executed, and the last thing that pops up is undefined

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-06-12 09:32:20

    var a;
    if(!(a in window)){

    var a = 1;

    }
    alert(a);
    if is not true, of course the code inside will not be executed, so there is nothing wrong with a being undefined

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-06-12 09:32:20

    if(!("a" in window)){
        var a = 1;
    }
    alert(a);

    When the JavaScript engine parses this code, it will be parsed as follows:

    var a ;
    if(!("a" in window)){
        a = 1;
    }
    alert(a);

    Because your a has been declared as a property of window, so the if condition is always false, and a is undefined if it is not assigned a value.

    reply
    0
  • Cancelreply