JS variable promotion
ES6(ES2105) has two important new keywords: let and const.
Variables declared by the let are valid only within the code block in which the let command resides.
Const declares a read-only constant. Once declared, its value cannot be changed.
This article mainly summarizes the difference between VAR and let
Var command
Variables declared by var will have variable promotion
(1) Declare the assignment statement after the print statement
console.log(bar); // undefined
var bar = 200;
// When the above code executes, the equivalent of
var bar;
console.log(bar);
bar = 200;
Copy the code
(2) Declare variable bar1 and assign the value 200, so print 200
var bar1 = 200;
console.log(bar1); / / 200
Copy the code
(3) Variables that are not declared using var are not put in VO objects, but just add a global attribute. So bar3 cannot be found in VO and an exception is thrown. And you can find it with this
console.log(bar3); // ReferenceError: bar3 is not defined
console.log(this.bar3); // undefined
bar3 = 100;
Copy the code
(4) Function declarations take precedence over variable declarations
function foo(){
console.log(f1); // [Function f1]
console.log(f2); // undefined
var f1 = 'hoisting';
var f2 = function(){};
function f1(){}
}
foo();
Copy the code
The let command
Variables declared by let do not have variable promotion
(1) Declare the assignment statement after the print statement
console.log(bar2); // ReferenceError: bar2 is not defined
let bar2 = 200;
Copy the code
(2) Let cannot be declared repeatedly
var a = 10;
var a = 20;
console.log(a); / / 20
let b = 100;
let b = 200;
console.log(b); // SyntaxError: Identifier 'b' has already been declared
Copy the code