// 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
// 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
块级作用域+ f+ _+ u& P5 k# L2 e
var不存在块级作用域,let和const存在块级作用域。 $ R, k2 [( V$ q8 { d
// 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
重复声明 4 L7 p$ ~ K% l- f. h- w5 k/ _ var允许重复声明变量,let和const在同一作用域不允许重复声明变量。 9 t/ Z6 Q% |; e' B- v
// 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
使用; T; e& f: U* ?$ E q( F# D+ w* V% p
能用const的情况尽量使用const,其他情况下大多数使用let,避免使用var。