什么是变量提升?

解释下变量提升?✨


JavaScript引擎的工作方式是,先解析代码,获取所有被声明的变量,然后再一行一行地运行。这造成的结果,就是所有的变量的声明语句,都会被提升到代码的头部,这就叫做变量提升(hoisting)。

console.log(a) // undefined

var a = 1

function b() {
    console.log(a)
}
b() // 1

上面的代码实际执行顺序是这样的:

第一步: 引擎将var a = 1拆解为var a = undefineda = 1,并将var a = undefined放到最顶端,a = 1还在原来的位置

这样一来代码就是这样:

var a = undefined
console.log(a) // undefined

a = 1

function b() {
    console.log(a)
}
b() // 1

第二步就是执行,因此js引擎一行一行从上往下执行就造成了当前的结果,这就叫变量提升。

原理详解请移步,预解释与变量提升

what's variable promotion ?

The way of javascript engine work is to parse the code first, getting all of varibales that be declared, and then run it line by line.

The result of that all variable delcaration statements will be promoted to the head of code, which is called variable hoisting.

console.log(a) // undefined

var a = 1

function b() {
    console.log(a)
}
b() // 1

the actual execution sequence of the above code is as follow:

Step 1: the engine will split var a = 1 to var a = undefined and a = 1, and place the var a = undefined to the top, a = 1 still in the original place.

This way of code is as follow:

var a = undefined
console.log(a) // undefined

a = 1

function b() {
    console.log(a)
}
b() // 1

Step 2 is execution, so the JS engine execute line by line from top to bottom cause the result of the present, which is called variable hoisting.

If you want to move to the detailed explanation of the principle, pre-explanation and variable promotion

你可能感兴趣的:(javascript,前端,html,面试技巧)