• Variables declared by var are mounted to window, while variables declared by let and const are not
var a = 'foo'
console.log(window.a) // foo

let b = 'bar'
console.log(window.b) // undefined

const c = 'baz'
console.log(window.c) // undefined
Copy the code
  • Var has variable promotion, but let and const do not. The area above let and const is called a “temporary dead zone” and cannot be used before definition
console.log(a) // undefined
var a = 'foo'

console.log(b) // test4.html:14 Uncaught ReferenceError: Cannot access 'b' before initialization
let b = 'bar'

console.log(c) // test4.html:14 Uncaught ReferenceError: Cannot access 'c' before initialization
const c = 'baz'
Copy the code
  • Declarations for let and const form block-level scope
if (true) {
    var a = 'foo'
    let b = 'bar'
}
console.log(a) // foo
console.log(b) // Uncaught ReferenceError: b is not defined

if (true) {
    var a = 'foo'
    const c = 'baz'
}
console.log(a) // foo
console.log(c) // Uncaught ReferenceError: c is not defined
Copy the code
  • In the same scope, let and const cannot declare the same variable again. Var can
var a = 'foo'
var a = 'bar'
console.log(a) // bar

let b = 'foo'
let b = 'bar'
console.log(b) // test4.html:34 Uncaught SyntaxError: Identifier 'b' has already been declared

const c = 'foo'
const c = 'bar'
console.log(c) // Uncaught SyntaxError: Identifier 'c' has already been declared
Copy the code
  • Let can be modified after it defines a variable, while const appears to declare a “constant.” Const does not guarantee that the value of a variable cannot be changed, but rather that the memory address to which the variable points cannot be changed. For simple data types (Number, String, Boolean), the value is stored in the memory address that the variable points to and is therefore equivalent to a constant; For complex data types (mainly objects and arrays), the variables simply hold the addresses to the heap memory, and it is not possible to control whether the data in the heap is mutable.
const person = {}
person.name = 'maoxiaoxing'
console.log(person) // {name: "maoxiaoxing"}

person = {name: 'king'} // test4.html:45 Uncaught TypeError: Assignment to constant variable.

const a = ['foo']
a.push('bar')
a[2] = 'baz'
console.log(a) // ["foo", "bar", "baz"]
Copy the code