1. Scope
Var variables defined by the scope is a function of the entire closed, the whole domain. Let variables defined in the scope of the block or sub-block level.
for (let i = 0; i < 10; i++) {
// ...
}
console.log(i);
// ReferenceError: i is not defined
// loop counter i for only effective in vivo, in vitro cycle error will reference
2. The variable lift phenomenon :
The browser before running the code will be pre-analytic, analytic function declaration first, the definition of variables, and then the function, variable run, assignments and other after parsing finish. Regardless of the variables var declared in the first few lines of the current scope, will be promoted to the head of scope. Var variable declaration will be raised to the top of the scope and initialization is undefined, and uninitialized variables let statement at the top of scope
// var situation of
console.log(foo); // 输出undefined
var foo = 2;
// equivalent
var foo; // declaration and initialization is undefined
console.log(foo);
foo=2;
// let the situation
console.log(bar); // 报错ReferenceError
let bar = 2;
// equivalent to the bar but not initialized in the first line of the first statement, until the assignment when initializing
But not directly assign variables are declared with let prints undefined, or initialized
let a;
alert (a); // value is undefined
alert b; // will complain
let b;
3. The block-level scope
As long as there is a block-level scope let command, variable declared it would "bind" in the region, no longer subject to external influences. Further, in the code blocks before the let command to declare variables, the variables are not available, despite the presence of the outer code blocks are also the same global variable.
Example 1:
was tmp = 123;
if (true) {
tmp = 'abc'; // ReferenceError
let tmp;
}
Example Two:
was tmp = 123;
if (true) {
//tmp = 'abc';
let tmp;
}
Alert (tmp); (assuming that no illegal use of the foregoing, there is no wrong throw) // output value is 123, the global and the local tmp tmp does not affect
4. let not allowed in the same scope, the statement repeated the same variable.
// error
function () {
let a = 10;
There are a = 1;
}
// error
function () {
let a = 10;
let a = 1;
}