I. Characteristics of VAR

  1. Improvement of existing variables
console.log(a); // undefined var a = 10; Var a; console.log(a); // undefined a = 10;Copy the code
  1. A variable can be declared multiple times, and subsequent declarations overwrite previous declarations
var a = 10; var a = 20; console.log(a); / / 20Copy the code
  1. When a variable is declared in a function using var, the variable is local
var a = 10; function change(){ var a = 20; } change(); console.log(a); / / 10Copy the code

If you do not use var inside a function, the variable is global

var a = 10; function change(){ a = 20 }; change(); console.log(a); / / 20Copy the code

2. Features of let

  1. There is no variable promotion, the variable cannot be used until let declares it (temporary dead zone)
console.log(a); // ReferenceError: a is not defined let
a = 10;
Copy the code
  1. The let command is valid within the code block where the let command resides, and is valid within the block-level scope
{ 
    let a = 10;
}
console.log(a); // ReferenceError: a is not defined
Copy the code
  1. Let does not allow repeated declarations in the same scope. Note that repeated declarations in different scopes do not report errors
let a = 10;
let a = 20; // Uncaught SyntaxError: Identifier 'a' has already been declared 
let a = 10;
{ 
    let a = 20;
} // ok
Copy the code

Three const.

  1. Const declares a read-only variable. Once declared, the value cannot be changed
const a = 10;
a = 20; // TypeError: Assignment to constant variable.
Copy the code
  1. Const must be initialized
const a; // SyntaxError: Missing initializer in const declaration 
const a = 10; // ok
Copy the code
  1. Const does not mean that the value of a variable cannot be changed, but rather that the data stored in the memory address to which the variable points cannot be changed
const obj = { 
    age: 17 
}
obj.age = 18; // ok
obj = { 
    age: 18
} // SyntaxError: Identifier 'obj' has already been declared
Copy the code
  1. Let has all the features of const

4. The difference between

  1. Variable ascension

    Var () {var (); var (); var (); var (); var (); var ()

  2. Block-level scope

    Var has no block-level scope. Let and const have block-level scope

  3. Repeat statement

    Var allows repeated declarations of variables let and const in the same scope do not allow repeated declarations

  4. Modify declared variables

    Var and let can declare a read-only constant const. Once declared, the value of the constant cannot be changed, but for reference types such as objects and data, the memory address cannot be changed, but the value inside can be changed.