foreword
This article mainly introduces the use and difference of var, const and let in ES6
basic introduction
let
- let declares variables
const
- const : Declare a constant
- Constants declared by const can be modified, but not reassigned
For example: the following code is correct:
//引用数据类型
const info ={
name:'Candy'
};
info.name='June';
And the following code is wrong:
//基本数据类型
const test ='hello';
test='world';
was
- declare variable
- let replaces var to declare variables
The difference between the three
1. Repeat statement
- Repeated declaration: that is, an existing variable or constant is declared again
- var allows repeated declarations, while let and const do not
- Example:
function func(a){
let a=1;
}
func();
The above code will report an error, because the variable a is declared twice, one is at the formal parameter of the function, and the other is declared inside the function, so an error will be reported.
2. Variable promotion
- var hoists variable declarations to the top of the current scope
- Example
code 1:
console.log(a)
var a=1;
Since var hoists the variable declaration to the top of the current scope, code 1 is equivalent to:
var a;
console.log(a)
a=1;
So the output is: undefined
3. Temporary dead zone
- As long as there are let and const in the scope, the variables or constants declared by them will automatically "bind" this area and will no longer be affected by the external scope
let a = 2;
function func){
console.log(a)
let a=1;
}
func();
Analysis: The above code will report an error
- First, functions only form a function scope when they are called;
- The variable let a is declared in the function, so the variable a will automatically bind the scope of the func function;
- When the console statement in the function is executed, since the variable a has been bound to the function scope, it is no longer affected by the external scope, that is, the value of the variable a outside the function is not used, and a has not been corrected when outputting a For declaration and assignment, an error will be reported.
4. Block-level scope
- Var has no block-level scope, while let and const have block-level scope
- Example
code 1:
for (var i=0;i<3;i++){
// console.log(i)
}
console.log(i)
result:
Code 2:
for (let i=0;i<3;i++){
// console.log(i)
}
console.log(i)
Result:
Analysis:
The block-level scope of the above code refers to the area between the curly braces of the function; since var has no block-level scope, the console statement outside the function can be executed normally; while let and const have block-level scope, Therefore, the console statement outside the function will report an error.