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
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <p id="demo"></p> <script> x = 5; // 变量 x 设置为 5 elem = document.getElementById("demo"); // 查找元素 elem.innerHTML = x; // 在元素中显示 x var x; // 声明 x </script> </body> </html>
Run the program and try it
##Example 2
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <p id="demo"></p> <script> var x; // 声明 x x = 5; // 变量 x 设置为 5 elem = document.getElementById("demo"); // 查找元素 elem.innerHTML = x; </script> </body> </html>Run the program and try it
JavaScript initialization will not be promoted
Instance 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>
Run the program and try it
<!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>
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.