Take a look at the code first:
(function() { var x = y = 1;}) (); Console.log (y); Console.log (x) ;
At first, I thought the problem was just a split question, and it was obvious that the result was, y=1;x=1
Then when I'm out of the console, I feel a loud slap, and the output:
Conclusion: The above results are due to variable elevation and even assignment .
Analysis: the above var X=y=1 easy to understand as Var x=y,var y=1; Because here the use of even equal assignment, even the operator assignment is from right to left, equivalent to Y=1; var x =y;
And then because of the variable promotion, will all the declaration ahead of time (just declaration ahead, assignment is not advanced) to the top of the function body, var x=y=1, the actual equivalent ofvar A; y=1; var x=y;
So the above code Console.log (y) has a value of 1 because Y=1 is not declared inside the function body with Var, so it is not a local variable, it is a global variable.
Note: ① variables that are not declared with VAR are global variables; ② declares the variable with Var, but outside the function body, there is no global variable in the function body.
A variable that is ③ in the function body but not declared with VAR is also a global variable, and the variable declared with VAR is the local variable ④ in the function body.
The ⑤ variable promotion is only declared forward to the top of the function body, and the assignment does not advance
Perhaps you will ask, that Console.log (x) above why not output undefined, but error?
Calling a variable that is not declared in the scope will cause an error. A variable is undefined only if it is declared but not assigned. Here the variable x is not declared in the global scope, does not exist, so will error!
Therefore, it is suggested that we should try not to use even such assignment, there will be many hidden dangers
JS even the trap of assigning value