Recently, I was looking at a new book called "You Don't know the volume of JavaScript." It's a coincidence to buy this book, but it's worth it. It gives a very deep description of JS's advanced concepts and makes us understand it through some easy-to-understand ways. This article is to solve the problem that has been bothering me with the JS declaration of Ascension. Here are some of my summaries and some notes.
Let's start with an example.
A= 2; var A;console.log (a);
Seeing this example reminds me of something that has been bothering me for a long time. In the preceding statement and in the following declaration, there are sometimes different effects. But I've never been careful to study it.
There may be some friends here who think it might output undefined. Because the second row of variables is re-assigned to the relationship.
But the result is that this will output 2;
Let's not worry about one more example.
Console.log (a); var a = 2;
This example I believe some people would think might be output 2 It is also possible that some people think that Var A is not declared before Console.log so it throws Referenceerror error.
But the result is the output is undefined;
The reason for this is to discuss the behavior of the JavaScript compiler in this area.
When the compiler sees
var a = 2;
Such statements will not be as we understand, the one go is to declare a and the assignment at the same time to pay attention to this sentence is very important
Instead, he split it into
var= 2;
To take a look. The first statement that Var a will be made at compile time, and the remaining assignment statements will be left in place to wait for the execution phase to execute.
So by understanding this logic, you may understand why the above behavior occurs. Here I analyze the second example.
The second example will be treated as a var = 2;
This executes. So the result of the output is undefined because it has been declared and has no value.
"This process is as if the variables and function declarations were moved from their position in the code, and this process is called ascension"--a reference to the volume of JavaScript you don't know.
Finally notice that a place, whether it is a function declaration or a variable declaration, is promoted, and the function declaration is first raised here to be careful.
A summary and reflection on the concept of JavaScript ascension.