[Javascript] ES6 — var, let and const
4 min readJun 6, 2017
在ES6的語法中,多了 let
和 const
2種宣告變數與常數的語法。他們和 var
的差別在於, var
是 function scoped,而 let
和const
是 block scoped。
let points = 50;
let winner = false;if(points > 40) {
let winner = true;
}> winner
<- false
上面的程式中,因爲 let
是 block scoped,所以if裡面的winner和外面的winner是不同的變數。而在同一個scope下,同樣名稱的 let
和const
只能宣告一次。
const
是用來宣告常數,而值是不能改變的:
const MY_AGE = 27;
MY_AGE = 20; // this will throw an error
console.log('my age is: ' + MY_AGE); // 27
但,object的屬性除外:
const person = {
name: 'Peyton',
age: 18
}> person = { age: 38 }
<- Uncaught TypeError: Assignment to constant variable.
> person.age = 38
<- 38
> person.age
<- 38
如果要強迫屬性也不能改變,可以使用 freeze
const peyton = Object.freeze(person)
以往使用 var
宣告時,爲了防止和global scoped的變數互相影響,需使用Immediately-Invoked Function Expression (IIFE),將 var
變數包在function的scope中。
(function() {
var name ='Peyton';
})();
但在ES6中,因爲 let
和const
是 block scoped 所以可以使用
{
const name = 'Peyton';
}
let 範例
以往使用 var
宣告 loop 裡的變數時,可能會產生下面問題
for(var i = 0; i < 10; i++) {
setTimeout(function(){
console.log(`The number is ${i}`)
}, 1000);
}
<- (10)The number is 10
改用 let
for(let i = 0; i < 10; i++) {
setTimeout(function(){
console.log(`The number is ${i}`)
}, 1000);
}
<- The number is 0
<- The number is 1
<- The number is 2
<- The number is 3
<- The number is 4
<- The number is 5
<- The number is 6
<- The number is 7
<- The number is 8
<- The number is 9
Dead Zone
必須先宣告才可呼叫
console.log(pizza);
const pizza = 'Margherita';
<- Uncaught ReferenceError: pizza is not defined
var, let and const 的使用時機
- use
const
by default - only use
let
if rebinding is needed - (
var
shouldn't be used in ES6)
出處:
參考: