What is JavaScript variable lift, frequently asked interview

JavaScript variable lift

Lift (Hoisting) JavaScript statement will move to the top of the default behavior.

JavaScript statement lift, in JavaScript, the variables can be declared after use. Put another way; variables can be used before it is declared. Example 1 Example 2 are given the same result:

Example 1:

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>js</title>
<body>

<p id="demo"></p>

<script>
    x = 5; // 给x赋值5

    elem = document.getElementById("demo"); // 查找一个元素
    elem.innerHTML = x;           // 在元素内显示x

    var x; // 声明 x
</script>

</body>
</html>

Example 2

!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>js</title>
<body>

<p id="demo"></p>

<script>
    var x; // 声明 x
    x = 5; // 把5赋值给x

    elem = document.getElementById("demo");
    elem.innerHTML = x;
</script>

</body>
</html>

To understand this, you must understand "the statement lift (English: Hoisting)" word. JavaScript statement refers to all move to the default behavior of the current top of the range (or the top of the script to the current the current function) of.

But in a change in the ES6 this default behavior, ES6 the let variable declaration and the const statement constants will not be lifted!   Worth learning and let const

JavaScript initialization not improve

JavaScript statements speak only enhance, rather than initializing. Example 1 and Example 2 are different results:

Example 1:

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>js</title>
<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>

Example 2

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>js</title>
<body>

<p id="demo"></p>

<script>
    var x = 5; // 初始化 x

    elem = document.getElementById("demo"); // 查找一个元素
    elem.innerHTML = x + " " + y;       // 显示x和y

    var y = 7; // 初始化 y

</script>

</body>
</html>

Declare your variables at the top!

For many developers, the variable lift (Hoisting) is an unknown or neglected JavaScript behaviors. If developers do not understand the upgrade, the program may contain errors (Error). To avoid errors, always declare all variables at the beginning of each range. Since this is interpreted JavaScript code that way, so it is always a good rule.

JavaScript in strict mode if you do not declare a variable, the variable is not allowed.

Guess you like

Origin blog.51cto.com/13578973/2421252