在ES6中,新出了let和const這兩個新的聲明變量的命令。與之前的var相比,let和const有幾個不同的特性。
var
- 可以重復聲明,且存在變量提升
- 沒有塊級作用域
<!--可以重復聲明--> var a = "this is a"; var a = "this is another a"; //重復聲明了a console.log(a); //輸出this is another a <!--存在變量提升--> console.log(b); //變量提升,var b 被提升至所在作用域頂部,輸出undefined var b = "this is b"; <!--無法限制修改--> var c = "this is c"; c = "this is cc"; c = "this is ccc"; console.log(c); //輸出this is ccc <!--沒有塊級作用域--> { var d = "this is d"; console.log(d); //輸出this is d } console.log(d); //輸出this is d
let
1.不能重復聲明,且不存在變量提升
2.塊級作用域
<!--不能重復聲明--> let a = "this is a"; let a = "this is another a"; //這里會報錯:Uncaught SyntaxError: Identifier 'a' has already been declared <!--沒有變量提升--> console.log(b); let b = "this is b"; //這里會報錯:Uncaught ReferenceError: b is not defined <!--塊級作用域--> { let c = "this is c"; console.log(c); //輸出this is c } console.log(c); //這里會報錯:Uncaught ReferenceError: c is not defined
const
const包含let的所有特性,區別是聲明的變量不可以修改(const保證變量指向的內存不可改動,而不是聲明的值不能改動)
<!--不能更改值--> const a = "this is a"; a = "b"; console.log(a); //這里報錯:Uncaught TypeError: Assignment to constant variable.