JavaScript: var and let

Jayson Chiang
Dec 8, 2020

--

如果直接使用未宣告的變數,會得到 Error。

console.log(x); // Error: Uncaught ReferenceError: x is not defined

一般情況,先用 var 宣告變數,並賦值。

var x = 6;
console.log(x) // 6

如果只宣告,但不賦值,會得到 undefined。note: undefined 並非 Exception。

var y;
console.log(y) // undefined

若在 var 宣告之前使用該變數,一樣會得到 undefined。非常不符合預期。

console.log(z); // undefined
var z = 6;

理由是因為 JavaScript 的 var 宣告有 Hoisting,下面的 code 和上面的結果是一樣的。

var z;
console.log(z);
z = 6;

為了避免var宣告造成的混亂,於是有了 let 和 const。一般來說 let 可以完全取代var,而且避免 Hoisting 的混亂;因為若在 let 宣告之前就使用該變數,執行階段會是得到 Error 非賦與 undefined。

let foo;
console.log(foo); // undefined
console.log(bar);
// Uncaught ReferenceError:
// Cannot access 'bar' before initialization
let bar;

另外要注意的是,雖然和本文一開始提到,使用未宣告的變數時,同樣得到 Uncaught ReferenceError,但錯誤訊息卻是 Cannot access ‘bar’ before initialization。這意思表示,編譯器其實知道程式後面有宣告這個變數,只是無法使用。

--

--

No responses yet