Repeat statement | Variable ascension | Temporary dead zone | Properties and methods of the window object | Block-level scope | |
---|---|---|---|---|---|
explain | An existing variable or constant is declared again | Promote the declaration of a variable to the top of the current scope | As long as lets and const are in scope, the declared variables or constants are automatically “bound” to the scope and are no longer affected by the external scope | In the global scope, variables declared by var and functions declared by function automatically become properties or methods of the Window object | Scope chain: Inner scope -> outer scope ->… -> Global scope |
let | Don’t allow | There is no | / | Will not be | There are |
const | Don’t allow | There is no | / | Will not be | There are |
var | allow | There are | There is no | / | There is no |
The var keyword
1. Var declares scope
A variable defined using the var operator becomes a local variable of the function that contains it. This variable will be destroyed when the function exits. But, by omitting var when defining variables inside a function, creates a global variable that can be accessed outside the function (not recommended).
2. The var declaration is improved
Variables declared using var are automatically promoted to the top of the function scope
Let the statement
The most obvious difference between let and VAR is that the scope of the LET declaration is block-level scope, while the scope of the var declaration is function scope. (Block-level scope is a subset of function scope)
1. Temporary dead zones
Let does not promote variables. Performing a moment before a LET declaration is called a “temporary dead zone”
2. Global declaration
Different from VAR. Variables declared in global scope using let do not become properties of Windows objects
3. Let declaration in the for loop
With let, iteration variables are scoped only inside the for loop
Const statement
Const behaves essentially the same as let. The important difference is that when a variable is declared with const, it must also be initialized
- Be sure to assign an initial value
const A; / / an error
- Constants are generally capitalized
- The value of constants cannot be modified
const TEAM = ‘livepool’; TEAM = ‘BACA’; / / an error
- Block-level scope
- Element changes to arrays and objects do not count as changes to constants
const TEAM = [‘MESSI’,’SUAREZ’,’NEYMAR’]; TEAM.push(‘VIDAL’); / / is not an error