undefined

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

undefined 全域性屬性代表原始值 undefined。它是 JavaScript 的原始型別之一。

試一試

function test(t) {
  if (t === undefined) {
    return "Undefined value!";
  }
  return t;
}

let x;

console.log(test(x));
// Expected output: "Undefined value!"

原始值 undefined

undefined 的屬性特性
可寫
可列舉
可配置

描述

undefined全域性物件的一個屬性。也就是說,它是一個全域性作用域中的變數。

在所有非傳統瀏覽器中,undefined 是一個不可配置、不可寫的屬性。即使情況並非如此,也應避免覆蓋它。

尚未賦值的變數的型別是 undefined。如果被評估的變數沒有賦值,方法或語句也會返回 undefined。如果函式沒有返回值,它也會返回 undefined

注意:儘管你可以在全域性作用域之外的任何作用域中使用 undefined 作為識別符號(變數名)(因為 undefined 不是保留字),但這樣做是一個非常糟糕的主意,會使你的程式碼難以維護和除錯。

js
// DON'T DO THIS

(() => {
  const undefined = "foo";
  console.log(undefined, typeof undefined); // foo string
})();

((undefined) => {
  console.log(undefined, typeof undefined); // foo string
})("foo");

示例

嚴格相等與 undefined

你可以使用 undefined 以及嚴格相等和不等運算子來判斷變數是否有值。在下面的程式碼中,變數 x 未初始化,if 語句評估為 true。

js
let x;
if (x === undefined) {
  // these statements execute
} else {
  // these statements do not execute
}

注意:此處必須使用嚴格相等運算子(而不是標準相等運算子),因為 x == undefined 還會檢查 x 是否為 null,而嚴格相等不會。這是因為 null 不等同於 undefined

有關詳細資訊,請參閱相等比較和相同性

typeof 運算子與 undefined

或者,可以使用 typeof

js
let x;
if (typeof x === "undefined") {
  // these statements execute
}

使用 typeof 的一個原因是,如果變數未宣告,它不會丟擲錯誤。

js
// x has not been declared before
// evaluates to true without errors
if (typeof x === "undefined") {
  // these statements execute
}

// Throws a ReferenceError
if (x === undefined) {
}

然而,還有另一種選擇。JavaScript 是一種靜態作用域語言,因此可以透過檢視變數是否在封閉上下文中宣告來判斷它是否已宣告。

全域性作用域繫結到全域性物件,因此可以透過檢查全域性物件上的屬性是否存在來檢查全域性上下文中的變數是否存在,例如使用 in 運算子。

js
if ("x" in window) {
  // These statements execute only if x is defined globally
}

void 運算子與 undefined

void 運算子是第三種選擇。

js
let x;
if (x === void 0) {
  // these statements execute
}

// y has not been declared before
if (y === void 0) {
  // throws Uncaught ReferenceError: y is not defined
}

規範

規範
ECMAScript® 2026 語言規範
# sec-undefined

瀏覽器相容性

另見