Recently, when looking at the foreign front-end code, I found that the new features of ES6 have become quite popular, especially let, and the applications are very common.
Although the usage of let is the same as var, it has improved a lot in terms of syntax and semantics and performance. Let's compare it from these two aspects below
Syntax>>
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, all of which define variable i to count, and the execution result is as follows:
outer i: 0
inner i: 0
inner i: 1
You can see that 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 may cause an error if you accidentally
Now change var to 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 result is:
outer i: 0
inner i: 0
inner i: 1outer i: 1
inner i: 0
inner i: 1
It's normal, the inner and outer layers have no effect, because let makes the scope of the variable only within its own block.
Example 2
console.log(a);var a = 'hi';
The output result is undefined. Execution of log(a) is before declaring the variable. Why is there no error? Because the actual effect of these two lines of code is:
var a;console.log(a);a = 'hi';
When parsing JS code, the variable declaration will be prompted to the starting position, which is also confusing
After using let instead, there will be no problem, and an error will be reported directly.
console.log(a); // Uncaught ReferenceError: a is not definedlet a = 'hi';
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 is 5ms, and the speedup is obvious
The above is the new grammar advantages of JavaScript6 let introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!