← Writing

Viiisit [JavaScript] - const, let, var!

在 JavaScript 裡,最常見的 const, let, var,這三者到底有什麼不同? Basics const 常數 在宣告常數上,要注意不能重複宣告也不能重新賦值,但是在宣告陣列或是物件時,可修改其內部屬性。 在第三點可以發現 const d = ["a", "b", "c"] 可以藉由...

javascript

在 JavaScript 裡,最常見的 const, let, var,這三者到底有什麼不同?

Basics

  • const 常數 在宣告常數上,要注意不能重複宣告也不能重新賦值,但是在宣告陣列或是物件時,可修改其內部屬性。 在第三點可以發現 const d = ["a", "b", "c"] 可以藉由取 index 的方式,更換陣列裡的元素。
// 1. constant declaration
const a = 2;
console.log(a); // 2

// 2. const cannot be re-assigned!
//example 1
const b = 2;
b = 3; // Uncaught TypeError: Assignment to constant variable.
console.log(b);

//example 2
const c = ["a", "b", "c"];
c = ["a", "b", "c"]; // Uncaught TypeError: Assignment to constant variable.
console.log(c);

// 3. const can changed by index
const d = ["a", "b", "c"];
d[0] = 333;
console.log(d); // [333, 'b', 'c']
  • let 宣告在當前區塊的變數

  • var 宣告一個變數

    let 與 var 都是可以用來宣告變數的,差異在:

    1. var 可以重複宣告,let 則不行
    2. 作用域 (scope) 不同 let 作用於 block scope ; var 作用於 function scope。
    var a = 1;
    var a = 1;
    console.log(a); // 1
    
    let b = 1;
    let b = 1;
    console.log(b); // Uncaught SyntaxError: Identifier 'b' has already been declared
    
    var c = 1;
    let c = 1;
    console.log(c); // Uncaught SyntaxError: Identifier 'c' has already been declared
    
    let d = 1;
    var d = 1;
    console.log(d); // Uncaught SyntaxError: Identifier 'd' has already been declared
    

變數應當宣告後再使用,避免使用無宣告變數

有宣告與沒宣告變數差別在是否可以 delete (一個刪除物件的運算) delete operator: removes a property from an object.

下方例子說明,無宣告的變數會被當作物件屬性新增,容易在 coding 上誤刪造成 bug,因此回歸到標題所述, 變數應當宣告後再使用,避免使用無宣告變數

var user = "小明";
delete user; // false

user = "小明";
delete user; // true

應當常使用 const, let 而非 var

const 的規則相較 let, var 嚴謹許多,因此在宣告上比較不會有重複的狀況。 透過上面的說明,可以知道 let 與 var 很相似,但是! var 沒做好管理,容易發生變數相互覆蓋,最嚴重的情形便是全域汙染,因此在使用上要小心。

使用上的方法,可以參考 Google 的說明:Google JavaScript Style Guide

Brief Summary

| - | var | let / const | | :--------------------------------: | :------------: | :------------------: | | Variable Hoisting | yes | yes TDZ | | Scope | function scope | block scope | | Repeated declaration | yes | no | | Influence to Global attributes | yes | no |


參考資料

MDN ㄚ建的技能樹 ExplainThis