1. 程式人生 > 實用技巧 >var、let、const三種宣告變數方式之間的差異

var、let、const三種宣告變數方式之間的差異

var、let、const三種宣告變數方式之間的差異


  • var宣告的變數會掛載到window上,而let和const宣告的變數不會
var a = 'foo'
console.log(window.a) // foo

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

const c = 'baz'
console.log(window.c) // undefined
  • var 存在變數提升,而let和const不存在變數提升,let和const上面的區域稱為“暫時性死區”,在定義之前不可以使用
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'
  • let和const的宣告會形成塊級作用域
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
  • 在同一個作用域下,let和const不能再次宣告同一個變數,而var可以
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
  • let定義變數之後可以修改,而const表面上像是宣告一個“常量”。const並不是保證變數的值不得改動,而是指變數指向的記憶體地址不得改變。對於簡單資料型別(Number、String、Boolean),值就儲存在變數指向的記憶體地址,因此等同於常量;而對於複合資料型別(主要是物件和陣列),變數只是儲存了指向堆記憶體的地址,至於堆內的資料是不是可變的,就不能控制了。
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"]