What's new in ES6 - let

The difference between let and var

Before ES6, we used var to declare variables, and JS only has function scope and global scope, without block level scope, so {} cannot limit the access scope of var declared variables

{ 
  var i = 9;
} 
console.log(i);  // 9

The new let in ES6 can declare variables of block level scope.

{ 
  let i = 9;     // i variable is only valid in curly braces!!!
} 
console.log(i);  // Uncaught ReferenceError: i is not defined

var details:

① Can var be omitted

In general, var can be omitted, but there are two points worth noting:
1. var a=1 and a=1, these two statements generally have the same effect. But the former cannot be deleted with delete. However, in most cases, this difference can be ignored.
2. Inside the function, if it is not declared with var, the created variable is a global variable, not a local variable.
Therefore, it is recommended to add var keyword to variable declaration.

② Variable promotion

The JavaScript engine works by parsing the code, getting all the declared variables, and then running line by line. As a result, all variable declaration statements will be promoted to the head of the code, which is called variable lifting.

Example:

console.log(a);
var a =1;

The above statement will not report an error, but will prompt undefined. Actual operation process:

var a;
console.log(a);
a =1;

Indicates that the variable a has been declared but has not been assigned. However, variable promotion is only valid for variables declared by var command. If a variable is not declared by var command, variable promotion will not occur.

console.log(aa);
aa =1;

Like ordinary variables, the function in js can also be regarded as a variable, and there is also variable promotion:

a();

function a(){
    console.log(1);
};

On the surface, the above code seems to call function a before declaration. But in fact, due to "variable promotion", the function a definition part is promoted to the code header, that is, it has been declared before the call. However, if a function is defined with an assignment statement, JavaScript will report an error:

a();

var a = function(){
    console.log(1);
};

// TypeError: a is not a function

Because the actual operation process:

var a;
a();

a = function(){
    console.log(1);
};

At this time, a is a variable, not a function.

The above code will report an error: ReferenceError: aa is not defined.

Related interview questions: common variable improvement of var

var a = 99;            // Global variable a
f();                   // f is a function. Although it is defined after the call, the function declaration will be promoted to the top of the scope. 
console.log(a);        // A = > 99, which is the a of the global variable
function f() {
  console.log(a);      // The current a variable is the following variable. After the a declaration is promoted, the default value is undefined
  var a = 10;
  console.log(a);      // a => 10
}

// Output result:
undefined
10
99

let detailed explanation

① Unique application of let with for loop

let is well suited for block level scope inside a for loop.
The for loop body in JS is special. Each execution is a new independent block scope. After the variables declared with let are passed into the scope of the for loop body, they will not change and will not be affected by the outside world. Look at a common interview question:

for (var i = 0; i <10; i++) {  
  setTimeout(function() {  // Synchronously register the callback function to the asynchronous macro task queue.
    console.log(i);        // When this code is executed, the synchronization code for loop has been executed
  }, 0);
}
// Output results
10   10 in total
// Knowledge points: JS event loop mechanism, setTimeout mechanism, etc

If you change var to let declaration:

// Although i is declared in the global scope, when it is used in the local scope of the for loop body, the variable will be fixed and free from external interference.
for (let i = 0; i < 10; i++) { 
  setTimeout(function() {
    console.log(i);    //  i is the local scope in the circulatory system, which is not affected by the outside world.
  }, 0);
}
// Output result:
0  1  2  3  4  5  6  7  8 9

② let has no variable promotion and temporary deadband

For variables declared with let, there is no variable promotion. Moreover, the variable can only be used after the let declaration statement is executed, otherwise an Uncaught ReferenceError error error will be reported.
For example:

console.log(aicoder);    // Error: Uncaught ReferenceError
let aicoder = 'aicoder.com';
// Here you can safely use aicoder

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 the code block, the variable is not available until it is declared with the let command. Grammatically, this is called "temporary dead zone"
TDZ).

③ let variables cannot be declared repeatedly

let is not allowed to declare the same variable repeatedly within the same scope. Otherwise, an error is reported: uncaught syntax error: identifier 'XXX' has already been declared
For example:

let a = 0;
let a = 'sss';
// Uncaught SyntaxError: Identifier 'a' has already been declared

reference resources:

https://www.cnblogs.com/52fhy/p/5117267.html
https://www.cnblogs.com/fly_dragon/p/8669057.html

Keywords: Javascript Front-end ECMAScript

Added by busyguy78 on Wed, 26 Jan 2022 18:29:53 +0200