JavaScript variable hoisting

What is the result of the following program?

    php中文网(php.cn)  

The result pops up: 10

    php中文网(php.cn)  

The result pops up: 1

Scares you, right? what's going on? This may be unfamiliar, dangerous, and confusing, but it is also actually a very useful and impressive JavaScript language feature - variable hoisting.



JavaScript initialization will not raise

JavaScript only declared variables will Promotion, initialization will not.

1.

    php中文网(php.cn) 

2.

    php中文网(php.cn) 

2's y outputs undefined, this is because the variable Declaration (var y) is hoisted, but initialization (y = 7) is not hoisted, so the y variable is an undefined variable.



Declare your variables in the header

For most programmers Didn't know about JavaScript variable hoisting.

If programmers do not understand variable promotion well, the programs they write will be 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!