In the js, to use the definition of the variable var operator, but var has many disadvantages, such as: can be repeated a variable declaration, not block-level scope, modifications and the like can not be restricted.
@ Disadvantage: declare variable can be repeated var A = 1 ; var A = 2 ; the console.log (A); // 2 // 2 disadvantage: it can not limit the modified @ disadvantages 3: no block-level scope { var B 12 is = ; } the console.log (B); // 12 is
ES6 new const and let you solve these problems. Let's take a look and let it const.
- let const and can not be repeated statement
let a=1; let a=2; console.log(b); //SyntaxError: Identifier 'a' has already been declared
- let statement is variable value can be modified; declared const is a constant and can not be modified
const a=1; a=2; console.log(a); //TypeError: Assignment to constant variable.
- There are block-level scope
var a=[]; for(var i=0; i<5;i++){ a[i] = function (){ console.log(i); } } a[2](); //5
In the above example, the variable var i is defined, the global scope is, only a global i, each cycle, the value of the variable i + 1 will, after the end of the cycle, i is 5. All members of the array a, a [0] ... a [4] i are the same inside, so that the final output is 5.
let a=[]; for(let i=0; i<5;i++){ a[i] = function (){ console.log(i); } } a[2](); //2
In this example, i is declared using let only effective block-level scope. Each member of a array has its own i.
Further, it is noted that, for that part of the circulating loop variable is set parent scope, the loop body is a separate sub-scope.
for(let i=0; i<2; i++){ let i=12; console.log(i); } //12 //12