1.let and Const commands
1.ES6 new Let and const commands, similar to Var usages, but the variables it declares are valid only within the code block where let is located (block-level scope, ES5 only global and function scopes)
{let a = 1; var b = 2; } //A is not a variable declared by defined let only within its own block valid //2
varA = []; for(AVR i = 0; i < ten; i++){A[i] =function() { Console.log (i) }; } A[3] ();//Ten //A[3]) () print out is 10,i is Var declaration, in the global scope is valid, so each cycle, the new I value will overwrite the old value, so the last I is ten varA = []; for(Let i = 0; i < ten; i++){A[i] =function() { Console.log (i) }; }A[3] ();//3 //a[3] () print out is 3, the variable i is let declaration, and only in the block-level scope valid, each I is a different scope, so the last output 3
2. There is no variable promotion
Variable promotion means to refer to the above, in JS, is defined in the back of things (variables or functions) to the previous definition.
Eg:var There will be variable elevation
var v= ' Hello ' (function var v= ' World ' })() ; // This code alert comes out of the undefined, because there is a variable promotion, the definition will refer to the previous, the assignment will not be promoted, the code after the variable promotion is as follows: var v= ' Hello ' (function var v; v= ' world ' ) () ;
There is no variable elevation using the Let command, so be sure to use it before declaring it.
3. Temporary Dead Zone
ES6 explicitly states that if a let and a const command exists in a chunk, the variables declared by the block on those commands form a closed scope from the outset. These changes are used before the declaration
, you will get an error.
var tmp = ' www ';
if (true) { tmp = ' abc '; // TMP is not defined Console.log (TMP); // tmp is not defined // undefined tmp = 123; // 123 }
ES6 uses let and const to avoid problems with the use of Var without declaring it.
4. Duplicate declarations are not allowed
// Here are some of the errors function () { = 1; var a = 2; } function () { = 1; = 2; } function Fun (Arg) {let arg; } // no error, two Arg belongs to different block-level scopes function Fun (Arg) { {let arg; } }
2. Block-level scopes
1. There is no block-level scope in ES5
///First scenario: Inner variables overlay outer variables
varTMP =NewDate ();functionf () {Console.log (TMP); if(false) { vartmp = ' Hello world! '}}f (); //undefined variable elevation, inner variable covers the outer variable///second scenario: The loop variable is leaked as a global variablevars = ' Hello '; for(vari = 0; i < s.length; i++) {Console.log (s[i]);} Onsole.log (i); //5 After the end of the loop I leaked to the global variable
Block-level scopes for 2.ES6, let and const
A pair of {} represents a block-level scope that can be arbitrarily nested
{{{= ' hello '} //}}}{{{= ' Hello '} = ' world '; // different scopes can define a variable with the same name }}}
ES6 Small White Study notes (i)