// 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
块级作用域. a/ e5 l# T7 k4 Z( a! P
var不存在块级作用域,let和const存在块级作用域。! |- O% K+ a" `1 E
// 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
重复声明5 j( X/ V0 Z6 q; L _) H
var允许重复声明变量,let和const在同一作用域不允许重复声明变量。 k# s/ b7 _3 s. E7 U
// 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
修改声明的变量 6 T' U: ]3 U# C6 j9 [$ w B var和let可以,const声明一个只读的常量。一旦声明,常量的值就不能改变。& P& u6 C2 U8 V& \) x. [; _3 E6 s: u
// 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