返回課程

變數是否可見?

重要性:4

這段程式碼的結果會是什麼?

let x = 1;

function func() {
  console.log(x); // ?

  let x = 2;
}

func();

附註:這項任務有一個陷阱。答案並不顯而易見。

結果是:錯誤

試著執行看看

let x = 1;

function func() {
  console.log(x); // ReferenceError: Cannot access 'x' before initialization
  let x = 2;
}

func();

在這個範例中,我們可以觀察到「不存在」和「未初始化」變數之間的特殊差異。

正如你可能在 變數範圍、封閉 一文中所讀到的,當執行進入程式碼區塊(或函式)時,變數會從「未初始化」狀態開始。它會保持未初始化狀態,直到對應的 let 陳述式出現。

換句話說,變數在技術上存在,但不能在 let 出現之前使用。

以上的程式碼示範了這一點。

function func() {
  // the local variable x is known to the engine from the beginning of the function,
  // but "uninitialized" (unusable) until let ("dead zone")
  // hence the error

  console.log(x); // ReferenceError: Cannot access 'x' before initialization

  let x = 2;
}

變數暫時無法使用的這個區域(從程式碼區塊開始到 let 結束)有時稱為「死亡區域」。