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

浏览器兼容性

另见