!!! Let's take a look at Ruan Yifeng's es6 explanation of this part. For example, let and const have the same five features. For example, const does not have the same effect. I omitted the var example, but I can find it in let. I don't like to write a long blog.
let
- The declared variable is only valid in the code block it is in;
- Variables will not be promoted (meaning that all variables need to be declared first and then used, otherwise an error will be reported)
- Temporary deadband (there is a let command in the block level scope, and the variables it declares are bound to this area and are no longer affected externally)
- Non repeatable statement
- Declared in the global, but not the properties of the global object;
for (let i = 0; i < 10; i++) {
console.log(i);
}
console.log(i); // i is not defined
for (var j = 0; j < 10; j++) {
console.log(j);
}
console.log(j); //10
//----------------------------
var tmp = 123;
if (true) {
tmp = 'abc'; // tmp not defined
let tmp;
console.log(tmp);
}
// ----------------------
console.log(foo); // undefined
var foo = 2;
console.log(bar); // Report errors
let bar = 2;
//----------------------
let a = 1;
let a = 1;// Error Identifier 'a' has already been declared
var a = 1;
let a = 1; // Error Identifier 'a' has already been declared
const a = 1;
let a = 1; // Error Identifier 'a' has already been declared
//------------------------
let a = 1;
console.log(window.a); // undefined
var
- global variable
- Variable lifting
- Repeatable statement
var a = 1;
var a = 2; // Executable
let b = 1;
var b = 1; // Error Identifier 'b' has already been declared
const c = 1;
var c = 1; // Error Identifier 'c' has already been declared
const
- Same as let (5 features)
- Const declares a read-only constant. Once declared, the value of the constant cannot be changed. Once const has declared a variable, it must be initialized and cannot be left for later assignment. If you use const to declare a variable, but do not assign a value, an error will also be reported;
- Note: for objects and arrays, the addresses they point to are the same and can be changed
const a; // Missing initializer in const declaration
//------------------------
const a = 1;
a = 2; //Error reporting Assignment to constant variable
console.log(a);
//--------------------
const a33 = [];
a33.push('Hello'); // Executable
a33.length = 0; // Executable
Here's the explanation. Next, I want to write some questions about var, let and const, which should be in another blog