First, scope

Var is a function scope that, once declared, is globally valid.

Let is a block-level scope, and an error is reported when a variable declared inside a code block is called outside the code block

{ let a = 10; var b = 1; }console.log(a); Console. log(b) //1Copy the code

Counters for the for loop, suitable for the let command; A special feature of the for loop is that the part that sets the variables of the loop is a parent scope, while the inside of the loop body is a separate child scope.

for (let i = 0; i < 3; i++) {
  let i = 'abc';
  console.log(i);
}
// abc
// abc
// abc
Copy the code

Second, whether there is variable promotion

Var has “variable promotion”, the variable can be used before the declaration, the value of undefined;

There is no variable promotion in let. Variables declared by let must be used after the declaration, otherwise an error will be reported.

// var case console.log(foo); Var foo = 2; // let's case console.log(bar); // ReferenceError let bar = 2;Copy the code

Three, can be repeated declaration

Var allows you to declare the same variable repeatedly in the same scope.

Let does not allow the same variable to be declared twice in the same scope.

// modifiers 'a' has already been declared function func() {let a = 10; var a = 1; } // modifiers 'a' has already been declared function func() {let a = 10; let a = 1; } function func() { var a = 10; var a = 1; //a:1 }Copy the code

Temporary dead zone

As long as a let command exists in a block-level scope, the variables it declares are “bound” to the region, free from external influence.

var tmp = 123; if (true) { tmp = 'abc'; // ReferenceError let tmp; } // All variables are "dead" until they are declared by the let command.Copy the code

Five, the other

Const command

Const declares a read-only variable. Once declared, the value of the constant cannot be changed. The address to which the complex type pointer points cannot be changed; the internal data can be changed.

Const PI = 3.1415; PI = 3; // TypeError: Assignment to constant variable.Copy the code

Once a const variable is declared, it must be initialized immediately and cannot be assigned later.

const foo;
// SyntaxError: Missing initializer in const declaration
Copy the code

Properties of the top-level object

Top-level objects: browser environment (Window object), Node (global object)

Assignment of attributes to top-level objects is the same thing as assignment of global variables.

Global variables declared by the var and function commands are still attributes of the top-level object.

Variables declared by let, const, and class that are not attributes of the top-level object

var a = 1; A // 1 let b = 1; // This. A window. A // 1 let b = 1; window.b // undefinedCopy the code