This article mainly introduces the let and const commands in the new features of ES6, and analyzes the functions, usage and related Precautions of the let and const commands in the form of instances, you can refer to this article to introduce the let and const commands in the new features of ES6, and analyze the functions, usage, and precautions of the let and const commands in the form of instances, for more information, see
This article describes the let and const commands in the new features of ES6. We will share this with you for your reference. The details are as follows:
1. let command
① In js, there is no block-level scope. The variable scope declared by var is the whole function body, And let can play this role.
{ let a = 1; var b = 2;}console.log(b); // 2console.log(a); // a is not defind
② Let can play this role. In js, the declaration of variables and functions will be promoted to the top execution of the current scope. This will cause problems.
Var a = []; // the function and variable I are declared first, and the global variable I is assigned as 10for (var I = 0; I <10; I ++) {a [I] = function () {console. log (I) ;};} console. log (I); // 10a [6] (); // 10
Let solves this problem.
for (let i = 0; i < 10; i++) { a[i] = function () { console.log(i); };}a[6](); //6
③ Let is not like var, and "variable escalation" will occur.
console.log(a); // a is not definedlet a = 1;
④ Let does not allow repeated declaration of the same variable within the same block-level scope
// Error {let a = 10; var a = 1;} // {let a = 10; let a = 1 ;}
2. const command
① Const is also used to declare variables, but it declares constants. Once declared, the constant value cannot be changed.
② Same as let, the same variable cannot be repeatedly declared in the same block-level scope.
③ Const has the same scope as the let command: it is only valid within the block-level scope of the declaration.
Const PI = 3.1415; console. log (PI); // 3.1415 // PI = 3; // Assignment to constant variable. (constants cannot be assigned) // const PI = 3.1; // Identifier 'Pi 'has already been declared
If you need to learn about js, please follow the first PHP community js video tutorial. You can watch many js online video tutorials for free!
The above are the new features of ES6 that you must understand: Detailed description of let and const commands. For more information, see other related articles in the first PHP community!