Let and const are new since ES6, along with new block-level scope ({} in braces)
I. Main differences:
Variables declared using var are scoped in the function in which the statement is located and are promoted. Variables declared using let are scoped in the code block in which the statement is located and are not promoted. Constants declared using const cannot be changed in subsequent code
Let and const cannot declare variables of the same name in the same scope. Var can hold a dead zone (the part between the top of the scope and the declaration position of the variable is the dead zone of the let variable. In the dead zone, access to the variable is prohibited. Therefore, there is no variable promotion for the variable declared by let, but we cannot access it before the declaration due to the dead band.
Analysis of two classic interview questions
var arr = []; for (var i = 0; i < 2; i++) { arr[i] = function () { console.log(i); } } arr[0](); //2 arr[1](); / / 2Copy the code
Arr [0]. Arr [0], output 2
let arr = []; for (let i = 0; i < 2; i++) { arr[i] = function () { console.log(i); } } arr[0](); //0 arr[1](); / / 1Copy the code
Since let has block-level scope, each loop generates a block-level scope. The variables in each block-level scope are different, and the function executes to output the value of I in its upper (the block-level scope generated by the loop) scope.
Two, the use of attention points
1. Var has variable promotion and global scope
(1) Variable promotion: the variable declaration is promoted to the front of the scope
console.log(num); var num=10; Var num; console.log(num); num=10;Copy the code
Note: the js method function also has variable promotion (2) global scope
for(var i=1; i<3; i++){ } console.log(i); For (let I =1; i<3; i++){ } console.log(i); //i is not definedCopy the code
2. Let declares variables
(1) The variables declared by let are only valid at the block level
if (true) {
let a = 10;
}
console.log(a) // a is not defined
Copy the code
Note: Variables declared using the let keyword have block-level scope. Variables declared using var do not have block-level scope. (2) There is no variable promotion
console.log(a); // a is not defined
let a = 20;
Copy the code
(3) Temporary dead zone
var tmp = 123; If (true) {// when TMP is declared let/const in the current block scope, the variable TMP will only be found in the current scope when assigned to 10. Error: TMP is not defined TMP = 10; let tmp; } // the console output TMP is not definedCopy the code
3, Const declares a constant. A constant is the amount that a value (memory address) cannot change.
After a constant is assigned, its value cannot be modified.
Const PI = 3.14; PI = 100; // Assignment to constant variable. const ary = [100, 200]; ary[0] = 'a'; ary[1] = 'b'; console.log(ary); // ['a', 'b']; ary = ['a', 'b']; // Assignment to constant variable.Copy the code
Ary = [‘a’, ‘b’]; ary = [‘a’, ‘b’]