var a = 20
let b = 20
const a = 30
const b = 30
// 都会报错
const实际上保证的并不是变量的值不得改动,而是变量指向的那个内存地址所保存的数据不得改动。对于简单类型的数据,值就保存在变量指向的那个内存地址,因此等同于常量。对于复杂类型的数据,变量指向的内存地址,保存的只是一个指向实际数据的指针,const只能保证这个指针是固定的,并不能确保改变量的结构不变。* z# c. `5 R& E% V( u O
// var
console.log(a) // undefined
var a = 10
// let
console.log(b) // Cannot access 'b' before initialization
let b = 10
// const
console.log(c) // Cannot access 'c' before initialization
const c = 10
暂时性死区. Z7 \. T2 w* ^) s v" a
var不存在暂时性死区,let和const存在暂时性死区,只有等到声明变量的那一行代码出现,才可以获取和使用该变量。5 x. D: C/ [5 L/ a
// var
console.log(a) // undefined
var a = 10
// let
console.log(b) // Cannot access 'b' before initialization
let b = 10
// const
console.log(c) // Cannot access 'c' before initialization
const c = 10
块级作用域# T0 g q }1 o9 L/ h7 v# W* o" V2 b
var不存在块级作用域,let和const存在块级作用域。3 O9 U. K Q7 K& i+ W, Y |* S0 _
// var
{
var a = 20
}
console.log(a) // 20
// let
{
let b = 20
}
console.log(b) // Uncaught ReferenceError: b is not defined
// const
{
const c = 20
}
console.log(c) // Uncaught ReferenceError: c is not defined
重复声明 ! B. a x( K9 K+ @ var允许重复声明变量,let和const在同一作用域不允许重复声明变量。5 L, ~2 p( f3 T5 Y' g4 @' }, i+ G
// var
var a = 10
var a = 20 // 20
// let
let b = 10
let b = 20 // Identifier 'b' has already been declared
// const
const c = 10
const c = 20 // Identifier 'c' has already been declared
// var
var a = 10
a = 20
console.log(a) // 20
//let
let b = 10
b = 20
console.log(b) // 20
// const
const c = 10
c = 20
console.log(c) // Uncaught TypeError: Assignment to constant variable
使用" H9 C3 A% V- v9 h' r
能用const的情况尽量使用const,其他情况下大多数使用let,避免使用var。