ES6 adds the let keyword, which differs from the var keyword as follows.
- variables declared by let are valid only within their code block.
- variables declared by var are valid globally.
- variables declared by var can be used before they are declared, while let does not allow it
- var runs duplicate declaration of variables, while let does not allow duplicate declaration of variables.
Declaring a variable a in a code block using the let keyword and testing a call to the variable a outside the code block results in an a is not defined exception.
{
let a = 0;
console.log(a);
}
console.log(a);
Declare a variable a in the code block using the var keyword, and test calling the variable a outside the code block; it is globally valid, so no exceptions will occur.
{
var a = 0;
}
console.log(a);
The “variable lifting” phenomenon is the undefined exception that occurs “before” the variable is called and the referenceError exception that occurs “after” the variable is called. This occurs with the var keyword, and let does not allow variables to be used first and declared later in this way.
console.log(a);
var a = 2;
console.log(b);
let b = 1;
The let keyword does not allow the same variable to be declared repeatedly in the same scope.
{
var a = 0;
let a = 1;
console.log(a);
}
// Or in this case
{
let a = 0;
let a = 1;
console.log(a);
}
Repeated declaration of variables using the var keyword is allowed, and the value of the last repeatedly declared variable overwrites the previous value.
{
var a = 0;
var a = 1;
console.log(a);
}