Make a summary every day, persistence is victory!
/** @date 2021-05-27 @description const and let. * /Copy the code
One (sequence)
Var,cosnt, and let have a variable promotion, while const and let have no promotion. However, as far as I know, coSNT and LET also have variable promotion, which is just different from var.
Ii (Explanation)
What is variable promotion? Js code can be divided into compilation phase and execution phase when it is running. Variable promotion occurs in compilation phase, which means that the declaration part of variables will be promoted to the top of the code during compilation. For example:
// Normal code.. var a = 1; // Var a; . . . a = 1; .Copy the code
So var a = 1; I used a, which is fine, but the value is undefined
console.log(a); // undefined
var a = 1;
Copy the code
Obviously, the above procedure is a difficult one to understand: why can I use a variable before it is declared? ES6 has added const and let declarations to correct this illogical error. Using a variable before the const and let declarations will cause an error:
console.log(a); // Uncaught ReferenceError: a is not defined
let a = 1;
Copy the code
Does this mean that there is no variable promotion for const and let? It’s not. Const and let are actually promoted, but they are only promoted by creation, as opposed to var, which is created and initialized, so the variable declared by var is called by undefined.
Three (insufficient)
The arrangement is not in place, and it is not clear from the above length why there is no variable improvement in LET and COSNT. After consulting the data, I will reconstruct the article.
Iv (Extended)
Other differences:
- Var can be defined repeatedly;
- Variables defined by var and let can be reassigned;
- Const and let have block-level scope;