This article describes the let and const commands in the new ES6 feature. Share it for your reference, as follows:
1. let command
① There is no block-level scope in js. The variable scope declared by var is the entire function body, and let can play this role
{ let a = 1; var b = 2; } (b); // 2 (a); // a is not defind
② Let can play this role. In js, the declaration of variables and functions will be promoted to the top of the current scope for execution. This will lead to problems.
var a = []; //The function and variable i will be declared first, and the global variable i will be assigned to 10 through the for loopfor (var i = 0; i < 10; i++) { a[i] = function () { (i); }; } (i);//10 a[6]();//10
Using let solves this problem
for (let i = 0; i < 10; i++) { a[i] = function () { (i); }; } a[6](); //6
③ Let is not like var, and there will be "variable improvement" phenomenon
(a); // a is not defined let a = 1;
④ Let does not allow repeated declaration of the same variable within the same block-level scope
// Report an error{ let a = 10; var a = 1; } // Report an error{ let a = 10; let a = 1; }
2. const command
① Const is also used to declare variables, but it is a constant. Once declared, the value of the constant cannot be changed.
② The same as let cannot be repeatedly declared within the same block-level scope.
③ The scope of const is the same as the let command: it is only valid within the block-level scope where the declaration is located.
const PI = 3.1415; (PI); // 3.1415 //PI = 3; // Assignment to constant variable. (The constant cannot be assigned a value)//const PI = 3.1;// Identifier 'PI' has already been declared
I hope this article will be helpful to everyone's ECMAScript programming.