JavaScript variable hoisting
In JavaScript, function and variable declarations will be promoted to the top of the function.
In JavaScript, variables can be declared after use, that is, variables can be used first and then declared.
The following two instances will achieve the same result:
Example 1
php中文网(php.cn)
Run the program and try it
##Example 2
Run the program and try itphp中文网(php.cn)
JavaScript initialization will not be promoted
Instance 1##
php中文网(php.cn)
Run the program and try it
php中文网(php.cn)
Run the program and try it
The y of instance 2 outputs undefined. This is because the variable declaration (var y) is increased, but the initialization (y = 7) will not be increased, so y variable is an undefined variable.
Tip
Declare your variables in the headerJavaScript variable hoisting is unknown to most programmers.
If programmers do not understand variable promotion well, the programs they write are prone to problems.
In order to avoid these problems, we usually declare these variables before the start of each scope. This is also a normal JavaScript parsing step and is easy for us to understand.