introduction
In ECMAScript, there are 3 keywords that can be used to declare variables. They are: var, let and const. Among them, var can be used in all ECMAScripts, but let and const need to be used in ECMAScript6 and above.
The behavior of let and const is basically the same, but there is a more important difference, that is, when const declares variables, the variable must be initialized at the same time, and trying to modify the variable declared by const will lead to a run error. Therefore, some people often directly understand that const is used to declare constants.
1: Scope
var is the function scope.
let and const are block-level scopes.
That is to say, the variable declared by var will be destroyed when it comes out of the function, while the variable declared by let and const will be destroyed inside the block level.
Here is an example of using for:
Variable declarations in for are also one of the differences between var and let.
for (var i = 0; i < 5; i++) { setTimeout(() => { (i); }, 0); } //5 5 5 5 5 for (var i = 0; i < 5; i++) { setTimeout(() => { (i); }, 0); } //0 1 2 3 4
The reason for this phenomenon is that var can penetrate into the outside of the loop body. When exiting the loop, the iterative variable saves the value that causes the loop to exit. Let's because the scope is inversely limited to the inside of the for loop block, the iterative loop declares a new variable, and each setTimeout refers to a different variable instance.
Two: Priority
There is no priority between the three keywords, in order of declaration.
Three: Differences in global declarations
The difference between let and var is that let will not become a property of a window object.
var name = "Matt". (); //Matt let name = "Matt" ();//undefined
Four: Variable improvement
This is an important difference between let and var, that is, the variables declared by let will not be promoted in scope.
(name); //undefined var name = "Matt"; (name); //ReferenceError: name is not defined let name = "Matt"
When parsing the code, the JavaScript engine will also notice the subsequent let (that is, the commonly mentioned "similar elevation behavior"), but the declared variable cannot be operated before this, otherwise you will be given a beautiful red ReferenceError. And this moment is also called a "temporary dead zone". It can also be regarded as limiting the code standard in some aspects.
other:
1. It is clearly stipulated in ES6 that if let and const appear in {}, they will be restricted to it (that is, block-level scope).
2. Function promotion has priority to increase variables with var (it is better not to have a duplicate name. If you think someone in your department will be more troublesome to share the name with you).
The above is the detailed explanation of the frequently asked questions and differences between var let const in ECMAScript. For more information on the differences between var let const in ECMAScript, please pay attention to my other related articles!