What is the result of the following program?
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> var foo = 1; function bar() { if (!foo) { var foo = 10; } alert(foo); } bar(); </script> </head> <body> </body> </html>
The result pops up: 10
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> var a = 1; function b() { a = 10; return; function a() {} } b(); alert(a); </script> </head> <body> </body> </html>
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.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <p id="demo"></p> <script> var x = 5; // 初始化 x var y = 7; // 初始化 y elem = document.getElementById("demo"); // 查找元素 elem.innerHTML = x + " " + y; // 显示 x 和 y </script> </body> </html>
2.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <p id="demo"></p> <script> var x = 5; // 初始化 x elem = document.getElementById("demo"); // 查找元素 elem.innerHTML = "x 为:" + x + ",y 为:" + y; // 显示 x 和 y var y = 7; // 初始化 y </script> </body> </html>
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.