Use of Let and Const
ES2015(ES6) adds two important JavaScript Keywords: let and const.
Let declared variables are only valid in the code block where the let command is located. const declares a read-only constant. Once declared, the value of the constant cannot be changed.
1. let command
The let command has the following features:
(1) Valid within code block
ES2015(ES6) adds two important JavaScript Keywords: let and const. Let declared variables are only valid in the code block where the let command is located. Const declares a read-only constant. Once declared, the value of the constant cannot be changed.
{ let a = 1; var b = 2; console.log(a);//Output 1 console.log(b);//Output 2 console.log(a);//Error ReferenceError: a is not defined console.log(b);//Output 2 }
(2) Declaration cannot be repeated
let can only be declared once. var can be declared multiple times:
let a = 1; let a = 2;//Error Identifier 'a' has already been declared var b = 3; var b = 4; console.log(a); console.log(b);//Output 4 for The cycle counter is very suitable for use let for (var i = 0; i < 10; i++) { setTimeout(function(){ console.log(i); }) } // Output ten 10 for (let j = 0; j < 10; j++) { setTimeout(function(){ console.log(j); }) } // Output 0123456789
The variable i is declared with var and is valid in the global range, so there is only one variable i in the global. In each cycle, i in the setTimeout timer refers to the global variable i, and the ten settimeouts in the cycle are executed after the end of the cycle, so i at this time is 10.
The variable J is declared with let. The current j is only valid in this cycle. In fact, j in each cycle is a new variable. Therefore, j in the setTimeout timer is actually a different variable, that is, the final output is 12345. (if the variable J of each loop is redeclared, how do you know the value of the previous loop? This is because the JavaScript engine will remember the value of the previous loop.).
(3) There is no variable promotion
let does not exist variable promotion, var will promote variable:
console.log(a); //ReferenceError: a is not defined let a = "apple"; console.log(b); //undefined var b = "banana";
Variable b is declared to have variable promotion with var, so when the script starts running, b already exists, but has not been assigned, so it will output undefined. Variable a uses let to declare that there is no variable promotion. Before declaring variable a, a does not exist, so an error will be reported.
(4) Temporary dead zone
As long as the let command exists in the block level scope, the variables declared by it will "bind" this area and will no longer be affected by the outside.
var tmp = 123; if (true) { tmp = 'abc'; // ReferenceError let tmp; }
In the above code, there is a global variable tmp, but the let in the block level scope declares a local variable tmp, which causes the latter to bind the block level scope. Therefore, an error will be reported when assigning a value to tmp before the let declares the variable.
ES6 clearly stipulates that if there are let and const commands in the block, the variables declared by the block for these commands form a closed scope from the beginning. If these variables are used before declaration, an error will be reported.
In short, within a code block, a variable is not available until it is declared using the let command. Syntactically, this is called "temporary dead zone" (TDZ).
if (true) { // TDZ start tmp = 'abc'; // ReferenceError console.log(tmp); // ReferenceError let tmp; // TDZ end console.log(tmp); // undefined tmp = 123; console.log(tmp); // 123 }
In the above code, before the let command declares the variable tmp, it belongs to the "dead zone" of the variable tmp.
"Temporary deadband" also means that typeof is no longer a 100% safe operation.
typeof x; // ReferenceError let x; In addition, the following code will also report an error, and var They behave differently. // No error reporting var x = x; // report errors let x = x; // ReferenceError: x is not defined
The error in the above code is also due to the temporary dead zone. When using let to declare a variable, an error will be reported as long as the variable is used before the declaration is completed. This is the case in the above line. Before the declaration statement of variable x is completed, it takes the value of X, resulting in the error "x undefined".
ES6 specifies that temporary deadband and let and const statements do not have variable promotion, mainly to reduce runtime errors and prevent the use of this variable before variable declaration, resulting in unexpected behavior. Such errors are common in ES5. With this provision, it is easy to avoid such errors.
In short, the essence of temporary deadband is that as soon as you enter the current scope, the variable to be used already exists, but it cannot be obtained. You can obtain and use the variable only when the line of code declaring the variable appears.
2. const command
const declares a read-only variable and cannot be changed after declaration. It means that once declared, it must be initialized, otherwise an error will be reported.
Basic usage:
const PI = "3.1415926"; PI // 3.1415926 const MY_AGE; // SyntaxError: Missing initializer in const declaration
The variable declared by const must not change its value, which means that once const declares the variable, it must be initialized immediately and cannot be assigned later.
const foo; // SyntaxError: Missing initializer in const declaration
The above code indicates that for const, if it only declares that it does not assign a value, an error will be reported. Const has the same scope as the let command: it is valid only within the block level scope where the declaration is located.
if (true) { const MAX = 5; } MAX // Uncaught ReferenceError: MAX is not defined
The constant declared by const command is not promoted, and there is also a temporary dead zone, which can only be used after the declared position.
if (true) { console.log(MAX); // ReferenceError const MAX = 5; }
The above code is called before the constant MAX declaration, and the result is an error. const is a constant declared. Like let, it cannot be declared repeatedly.
var message = "Hello!"; let age = 25; // The following two lines will report errors const message = "Goodbye!"; const age = 30;
Temporary deadband:
1var PI = "a"; if(true){ console.log(PI); //Error ReferenceError: PI is not defined const PI = "3.1415926"; }
ES6 clearly stipulates that if there is a let or const in the code block, the code block will form a closed scope for the variables declared by these commands from the beginning of the block. In the code block, using the variable PI before declaring it will report an error.
Key points for attention
How does const prevent variables from changing after declaration initialization? In fact, const does not guarantee that the value of the variable remains unchanged, but that the data stored at the memory address pointed to by the variable cannot be changed. At this point, you may have thought that simple types and composite types save values differently. yes, For simple types (numeric number, string, boolean), the value is stored at the memory address pointed to by the variable, so the simple type variable declared by const is equivalent to a constant, while the complex type (object, array, function). The memory address pointed to by the variable actually stores a pointer to the actual data, so const can only ensure that the pointer is fixed. As for the data structure pointed to by the pointer, it cannot be controlled. Therefore, be careful when using const to declare complex type objects.