The best JavaScript variable lift Tutorial In 2024, In this tutorial you can learn JavaScript initialization will not improve,Declare your variables in the head,
JavaScript, the function and the variable declaration will be raised to the top of the function.
JavaScript, variables can be declared after use, that is, variables can be declared before the first use.
The following two examples will get the same result:
To understand the above examples you need to understand "hoisting (variable lift)."
Variable Lift: function declarations and variable declarations will always be the interpreter quietly been "promoted" to the top of the method body.
JavaScript variable declarations will only increase, not initialized.
Results The following two examples are not the same:
Y Example 2 is outputundefined, this is because the variable declaration (var y) has improved, but the initialization (y = 7) does not increase, so the variable y is an undefined variable.
Example 2 is similar to the following code:
var x = 5; // 初始化 x var y; // 声明 y elem = document.getElementById("demo"); // 查找元素 elem.innerHTML = x + " " + y; // 显示 x 和 y y = 7; // 设置 y 为 7
For most programmers do not know JavaScript variable lift.
If the programmer is not well understood variables to enhance their written procedures prone to some problems.
To avoid these problems, we usually declare these variables before the beginning of each scope, this is normal JavaScript parsing step, easy to understand us.
JavaScript strict mode (strict mode) is not allowed to use an undeclared variable. In the next chapter we will learn to "strict mode (strict mode)". |