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
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:
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
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)){
}
alert(a);
if is not true, of course the code inside will not be executed, so there is nothing wrong with a being undefined
When the JavaScript engine parses this code, it will be parsed as follows:
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.