Introduction to the Advantages of JavaScript6 let New Grammar

  • 2021-07-04 17:46:17
  • OfStack

When looking at foreign front-end codes recently, we found that the new features of ES6 have been quite popular, especially let, which is very popular

Although the usage of let is the same as that of var, it has improved a lot both in syntax and semantics and in performance. Here is a comparison from these two aspects.

Grammar > >


for ( var i=0; i<2; i++){
console.log( 'outer i: ' + i);
for ( var i=0; i<2; i++){
console.log( 'inner i: ' +i);
}
}

This is a common nested loop, which defines the variable i to count, and the execution result is as follows:

outer i: 0
inner i: 0
inner i: 1

As you can see, the outer loop is interrupted because the value of i is modified by the inner loop. The usual solution is to use other variables in the inner loop, but it is possible that 1 accidentally made an error

Now replace var with let


for ( let i=0; i<2; i++){
console.log( 'outer i: ' + i);
for ( let i=0; i<2; i++){
console.log( 'inner i: ' +i);
}
}

The output is:

outer i: 0
inner i: 0
inner i: 1outer i: 1
inner i: 0
inner i: 1

Naturally, the inner and outer layers have no effect, because let makes the scope of variables only within their own blocks

Example 2


console.log(a);
var a = 'hi' ;

The output is undefined, and log (a) is executed before the variable is declared. Why didn't you report an error? Because the actual effect of these two lines of code is:


var a;console.log(a);
a = 'hi';

When parsing JS code, the declaration of variables will be prompted to the beginning position, which is also confusing

After switching to let, there will be no such problem and an error will be reported directly


console.log(a); // Uncaught ReferenceError: a is not definedlet 
a = 'hi' ;

Do a simple test of performance


var start = + new Date();
for ( var i = 0;i<1000000;i++){
var num = 123;
var str = 'abc' ;
var obj = {key: 'value' };
var arr = [ 'bill' , 'dell' ];
}
var end = + new Date();
console.log(end - start);

The average execution result under Firefox is 53ms

Change to let


'use strict'
var start = + new Date();
for ( var i = 0;i<1000000;i++){
let num = 123;
let str = 'abc' ;
let obj = {key: 'value' };
let arr = [ 'bill' , 'dell' ];
}
var end = + new Date();
console.log(end - start);

The average result was 5ms, and the speed increase was obvious


Related articles: