javascript - Why does the following code output "undefined"?
迷茫
迷茫 2017-06-12 09:30:20
0
6
764

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
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(6)
巴扎黑

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

Ty80
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

巴扎黑

I used your code and the result was popup 1

漂亮男人

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

给我你的怀抱

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

伊谢尔伦
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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template