This is the 7th day of my participation in the August More Text Challenge
A, let
1. Defined variables are valid only in code blocks
{ var a =20; } console.log(a); //20 { let a = 20; } console.log(a); // ReferenceError {let a =30; { console.log(a); / / 30}}Copy the code
2. Not accessible outside of the for loop
for(var i=0; i<3; i++){ } console.log(i); //3 for(let j=0; j<3; j++){ } console.info(j); / / ReferenceErrorCopy the code
3. There is no variable promotion
console.log(foo); Var foo = 2; console.log(bar); // ReferenceError let bar = 2;Copy the code
4. Temporary dead zones
Interpretation: As long as the let command exists in the block-level scope, the variables it declares are “binding” to the region and are no longer subject to external influence
var tmp = 23; if(true){ tmp = 'abc'; // ReferenceError let tmp; }Copy the code
The variable you want to use already exists as soon as you enter the current scope, but it cannot be retrieved until the line of code that declared the variable appears
5. You cannot redeclare parameters inside a function
{ let a = 10; let a = 20; console.log(a); // Error Duplicate declaration "a"}Copy the code
6. Sample
var a = []; for (var i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); // 10 is defined by var, which means that there is only one variable I globally. All the members of array A refer to the same I, so the output of the call is the value of the last round of I, i.e. 10Copy the code
The solution before ES6
var a = []; for (var i = 0; i < 10; i++) { (function(i){ a[i] = function () { console.log(i); }; }(I))} a[6](); / / 6Copy the code
var a = []; for (let i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); // the current I is only valid for this loop, so each loop I is a new variable, so the output is 6Copy the code
Second, the const
Const Declares a read-only constant. Once declared, the value of a constant cannot be changed
{ const a = 10; a = 20; console.log(a); //"a" is read-only }Copy the code
2. Declare that the value must be assigned
{ const a; // let a; Console. log(a); / / error}Copy the code
3. Object (reference type), can modify the assignment
{const obj = {user:" user "} obj. User = 'li si '; obj.pwd = '123455'; console.info(obj.user,obj); / / li si}Copy the code