Use of Let and Const
ES2015(ES6) has two important new JavaScript keywords: let and const.
Variables declared by let are valid only within the code block in which the let command is executed. Const declares a read-only constant, whose value cannot be changed once declared.
ES2015(ES6) has added two important JavaScript keywords: let and const. Variables declared by let are valid only within the code block in which the let command is executed. Const declares a read-only constant, whose value cannot be changed once declared.
{
let a = 1;
var b = 2;
console.log(a);/ / output 1
console.log(b);2 / / output
console.log(a);ReferenceError: A is not defined
console.log(b);2 / / output
}
Copy the code
(2) Do not repeat the statement
Let can only be declared once var can be declared multiple times:
let a = 1;
let a = 2;// The Identifier 'a' has already been declared
var b = 3;
var b = 4;
console.log(a);
console.log(b);/ / output 4
forCycle counters are good to uselet
for (var i = 0; i < 10; i++) {
setTimeout(function(){
console.log(i); })}// Output 10 10
for (let j = 0; j < 10; j++) {
setTimeout(function(){
console.log(j); })}/ / output 0123456789
Copy the code
The variable I is declared with var and is valid in the global scope, so there is only one variable I in the global scope. During each loop, the I in the setTimeout timer refers to the global variable I, while the ten setTimeout timers in the loop are executed after the loop ends. So I is going to be 10.
The variable j is declared with let, and the current j is only valid in this cycle. In fact, the j in each cycle is a new variable, so the j in setTimeout timer is actually a different variable, that is, the final output 12345. If the variable j is redeclared in each loop, how do I know the value of the previous loop? This is because the JavaScript engine internally remembers the value of the previous loop).
(3) There is no variable promotion
Let does not have variable promotion, var will have variable promotion:
console.log(a); //ReferenceError: a is not defined
let a = "apple";
console.log(b); //undefined
var b = "banana";
Copy the code
The variable b uses var to declare that there is a variable promotion, so when the script starts running, b already exists but has not been assigned, so undefined will be printed. Variable A uses let to declare that there is no variable promotion. Before variable A is declared, a does not exist, so an error is reported.
(4) Temporary dead zone As long as the let command exists in the block-level scope, the variables declared by it will be “binding” to this region and will no longer be affected by external influences.
var tmp = 123;
if (true) {
tmp = 'abc'; // ReferenceError
let tmp;
}
Copy the code
In the above code, there is a global variable TMP, but in the block-level scope, let also declared a local variable TMP, causing the latter to bind the block-level scope. Therefore, before let declared the variable, TMP assignment will report an error.
ES6 explicitly states that if there are let and const commands in a block, the variables declared by the block to those commands form a closed scope from the start. Any time these variables are used before declaration, an error is reported.
In short, the variable is not available within the code block until it is declared using the let command. This is grammatically known as a “temporal dead zone” (TDZ).
if (true) {
/ / start TDZ
tmp = 'abc'; // ReferenceError
console.log(tmp); // ReferenceError
let tmp; / / end of TDZ
console.log(tmp); // undefined
tmp = 123;
console.log(tmp); / / 123
}
Copy the code
In the above code, the TMP variable is in the “dead zone” of TMP until the let command declares it. A “temporary dead zone” also means that Typeof is no longer a 100 percent secure operation.
typeof x; // ReferenceError
letx; In addition, the following code will also report an error, andvarAre different in their behavior./ / is not an error
var x = x;
/ / an error
let x = x;
// ReferenceError: x is not defined
Copy the code
The above code error is also due to temporary dead zone. When declaring a variable with let, an error is reported whenever the variable is used before the declaration is complete. The above line is an example of this situation, where the value of x is fetched before the declaration of variable x is completed, causing an error “x undefined”.
ES6 makes it clear that temporary dead zones and let and const statements do not promote variables. The main purpose of ES6 is to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior. Such errors are common in ES5, and with this provision, it’s easy to avoid them.
In short, the essence of a temporary dead zone is that the variable you want to use already exists as soon as you enter the current scope, but you can’t get it until the line of code that declared the variable appears.
2. The const command const declares a read-only variable that cannot be changed. Means that once the declaration must be initialized, an error will be reported otherwise. Basic usage:
const PI = "3.1415926";
PI / / 3.1415926
const MY_AGE; // SyntaxError: Missing initializer in const declaration
Copy the code
A variable declared by const may not change its value, which means that a const, once declared, must be initialized immediately and cannot be left for later assignment.
const foo;
// SyntaxError: Missing initializer in const declaration
Copy the code
The code above shows that const is declared without assignment, and an error is reported. Const has the same scope as the let command: it is only valid in the block-level scope in which the declaration is made.
if (true) {
const MAX = 5;
}
MAX // Uncaught ReferenceError: MAX is not defined
Copy the code
Constants declared by the const command are also non-promoted and have temporary dead zones that can only be used after the declared position.
if (true) {
console.log(MAX); // ReferenceError
const MAX = 5;
}
Copy the code
The above code is called before the constant MAX declaration, and the result is an error. A constant declared by const, like let, cannot be declared repeatedly.
var message = "Hello!";
let age = 25;
// The following two lines will return an error
const message = "Goodbye!";
const age = 30;
Copy the code
Temporary dead zone:
1var PI = "a";
if(true) {console.log(PI); ReferenceError: PI is not defined
const PI = "3.1415926";
}
Copy the code
ES6 explicitly states that if there is a let or const in a code block, the code block will form a closed scope on the variables declared by those commands from the beginning of the block. Inside the code block, using the variable PI before declaring it will cause an error. How does const not allow a variable to change after it is declared initialized? A const ensures that the value of a variable is not changed, but that the memory address to which the variable points is stored is not changed. At this point, you might have figured out that simple types and compound types hold values differently. Yes, for simple types (number, string, Boolean), the value is stored at the memory address to which the variable points, so const simple type variables are declared as constants. For complex types (object, array, function), the memory address that a variable points to holds a pointer to the actual data, so const only guarantees that the pointer is fixed. So be careful when declaring objects of complex types using const.