Function scope and promotion

Before ES6 introduced let, variables were declared with var, and there was a saying of function scope. Use let to declare variables. Variables only exist after they are declared.
While using var to declare a variable, the variable can be called in the current scope, even before the declaration, the undeclared variable and the variable with the value undefined are not a concept. Using undeclared variables will report an error, but you can safely use existing variables with a value of undefined.

(Example 1) When using let, if the variable used is not declared, you will get an error

console.log(x)   // 错误终止
let x = 3;    

(Example 2) When using var, it can be called before the variable declaration

console.log(x)            // undefined
var  x = 3;    
console。log(x)            // 3

How did that happen? ? On the surface, it seems a little difficult to understand, because you can't access a variable that has not been declared.
In fact, the prompt mechanism used by var declared variables. JavaScript will scan the current scope, and any variable declared with var will be promoted to the top of the scope. The important thing to understand is that what is promoted is a declaration, not an assignment. So JavaScript will translate the code in our above (Example 2) into the following form.

var x  
console.log(x)
x = 3
console.log(x)

Guess you like

Origin blog.csdn.net/qq_44977477/article/details/108602210