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

    php中文网(php.cn) 

Run the program and try it


To understand the above example, you need to understand "hoisting (variable hoisting)".

Variable promotion: Function declarations and variable declarations are always quietly "promoted" to the top of the method body by the interpreter.


JavaScript initialization will not be promoted

JavaScript Only declared variables will be promoted, initialized ones will not.

The following two examples have different results:

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 header

JavaScript 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.


Continuing Learning
||
php中文网(php.cn)

submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!