Let's take a look at an interview question, and we'll guess what the result of this code is printed.
var name = ' world! ' ;( function () { if (typeof name = = = ' undefined ') {var name = ' Jack '; C11/>console.log (' Goodbye ' + name); Else { console.log (' Hello ' + name);
The result here is Goodbye Jack, not Hello world.
Because the JS code runs in two stages: the parsing phase and the execution phase
parsing phase: finds all declarations, including function declarations and VAR declarations , and promotes the declaration operation to the top of its execution environment (global or function), while assignment and logical operations are left in place for code execution.
Also, when it discovers a conflict between a function name and a function name or a function name and a variable name, the processing principle is: ' The handler overrides the declaration of the function, and the conflict is ignored when handling the variable declaration '. (Detailed later)
After the parsing phase, our code is actually parsed into this way:
var name = ' world! ' ;( function () { var// The declaration of the variable name is promoted to the top of the function, and the local variable name overrides the global variablename if ( typeof Name = = = ' undefined ') { = ' Jack '; Console.log (' Goodbye ' + name); Else { console.log (' Hello ' + name);
Execution Phase: assignment and logical operations are placed in the execution phase. So when we are in the execution phase, because the name variable declaration is promoted, in the If to Judge TypeOf name, the assignment operation (that is, name= ' Jack ') is not executed, so typeof name = = = ' undefined ' evaluates to True, The printed result is ' GoodBye Jack '.
And the Let,const in the new specification in ES6 will not perform variable promotion? I did a little experiment like that.
(function () { console.log (i);//undefined var i = ' Test const ';}) ();
(function () { console.log (i); // referenceerror:i is not defined Let i = 0;}) ();
(function () { /// referenceerror:i is not defined const i = ' Test const ' ;}) ();
You can see that the variables declared by let and Const are not promoted, which is why I marked the font red at first: function declarations and VAR declarations are promoted.
A detailed explanation of the parsing and execution phases of JS will be explained in the next blog post.
JavaScript variable boosts var let const, and JS parsing and execution phases