Each JS program execution will be divided into compilation stage and execution stage (assignment statement belongs to the execution stage) : compilation stage is to promote the declaration of JS variables to the front end of the current scope, it will generate a scope field, put all declared variables into scope. When executing the code, the scope is searched for the desired variables. Var declaration variables will be promoted to the front of the scope to generate var =undefined.

Come on: let’s look at the conclusion of the chart

The keyword Variable ascension Block-level scope Declare variables of the same name repeatedly To assign a value
var
let

Variable promotion:

Var */ console.log(num); Var num=10; / / run the above code is equivalent to the following writing / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / / / promotion code compilation process variables var num = undefined to the top of the scope / / / / statement execution code num = 10 Consosole.log (num) // undefined /* let declare variable */ console.log(b); B is not defined console.log(num1); // Error Cannot access 'num1' before initialization Let num1=10; / *Copy the code

From the let declaration variable, let has variable promotion, but cannot be initialized. If not, then our log(x) error is the same as the log(num1) error, but the var variable promotes the space object and the let space object does not exist together, let is in the temporary dead zone. The variable promotion declared by let exists but is not allowed to be used. Variable promotion is actually a bug. The generation of let is a solution to fix the variable promotion bug. Variable promotion is the operation mechanism of JS.

Block level scopes: ps: a pair of {} is a block level scope

{var a= 'hello'} cosole.log(a); Hello for(var I =0; i<5; I ++){}console.log(I)// output 5 let a='hello'} cosole.log(a)//ReferenceError: a is not defined for(let I =0; i<5; i++){ }console.log(i)//ReferenceError: i is not definedCopy the code

Var is block-scoped, while let is block-scoped

Duplicate declaration of variables with the same name:

Var a=10; var a=10; var a=100; console.log(a); //100 //let a=10; let a=100; console.log(a)//Identifier 'a' has already been declared var a=10; let a=20; console.log(a); // modifiers 'a' has already been declared // modifiers 'a' has already been declared { let a=100; } console.log(a); / / 10Copy the code

Reassign:

//let a=10; //let a=10; a=20; console.log(a)//20Copy the code