var to declare variables:
var only function scope, not block-level scope
// function scope performance function Test () { var I = 10 ; the console.log (I); // 10 } Test (); // 10 the console.log (I); // I IS Not defined; / / block-level scope no constraint var { var I = 10 ; the console.log (I); // 10 } the console.log (I); // 10
May be understood from the above code, block-level scope of var is not binding effect.
let declare variables:
Different let the var, let there be a block-level scope.
// block-level scope variables have declared constraints let { let I = 10 ; the console.log (I); // 10 } the console.log (I) // a ReferenceError
Understand the above characteristics look at, var, and let in a number of different manifestations of the for loop:
// var statement I function Test () { for ( var I = 0; I <2; I ++ ) { the setTimeout (() => { the console.log (I); }, 0 ); } } Test (); / / output: 2,2 & // the let statement I function Test () { for ( var I = 0; I <2; I ++ ) { the setTimeout (() => { the console.log (I); }, 0 ); } } Test (); // output: 0,1
You can see just not the same statement, the resulting output there is a huge difference.
Prior to this also we need to understand the setTimeout () implementation mechanisms:
setTimeout () is executed asynchronously. In the implementation of the for loop, a for loop is not executed immediately perform a setTimeout (), which makes setTimeout () to enter another thread to wait, when the main thread (this is test ()) after the implementation, setTimeout () then followed by execution.
When performed in var:
Since there is no block-level scope var, so i in a for loop statement will be present in the test () function scope. Each cycle will be declared once for i, but after the variable declaration will cover the variable declared earlier. Therefore, when the cycle is completed for (case setTimeout () has not been performed), the value of i becomes a function of the scope of the 2
The thread setTimeout () where is this:
// first push the setTimeout (() => { the console.log (I); }); // second push the setTimeout (() => { the console.log (I); });
I point i where i function scopes. Therefore, the outputs are 2.
When executed let in:
Because of block-level scope, the let i are present in the statement for block-level scope, for each loop generates a block-level scope. So setTimeout () in the thread is this:
{ let i=0; setTimeout(()=>{ console.log(i); }); } { let i=1; setTimeout(()=>{ console.log(i); }); }
So will once output 0,1;