JavaScript variable hoisting
JavaScript variable promotion
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 examples will obtain the same results:
x = 5; // 变量 x 设置为 5 elem = document.getElementById("demo"); // 查找元素 elem.innerHTML = x; // 在元素中显示 x var x; // 声明 x
var x; // 声明 x x = 5; // 变量 x 设置为 5 elem = document.getElementById("demo"); // 查找元素 elem.innerHTML = x; // 在元素中显示 x
The effects and results in the above two examples are the same.
To understand the above examples, 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:
Example 1:
var x = 5; // 初始化 x var y = 7; // 初始化 y elem = document.getElementById("demo"); // 查找元素 elem.innerHTML = x + " " + y; // 显示 x 和 y