// 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
暂时性死区4 |+ E0 J. y$ ]* u4 U# b
var不存在暂时性死区,let和const存在暂时性死区,只有等到声明变量的那一行代码出现,才可以获取和使用该变量。 $ C' z# |2 H$ f% q0 w+ G" _! N
// 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
块级作用域: b& q& j! M% R# d0 x
var不存在块级作用域,let和const存在块级作用域。 2 n& Q+ b5 w1 S' [. c+ U
// 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
重复声明 1 V# m) k2 e$ U" b& T var允许重复声明变量,let和const在同一作用域不允许重复声明变量。 * x1 T/ D2 d! n) b. d: G" v% [4 Q+ }
// 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
修改声明的变量 ( q4 y' i; M; D. m0 y; n, R var和let可以,const声明一个只读的常量。一旦声明,常量的值就不能改变。 / l6 u5 ]" D$ P; o
// 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