空值合并运算符 (??)

Baseline 已广泛支持

此特性已经十分成熟,可在许多设备和浏览器版本上使用。自 2020 年 7 月以来,它已在各大浏览器中可用。

空值合并运算符 (??) 是一个逻辑运算符,当其左侧操作数为 nullundefined 时,它返回其右侧操作数,否则返回其左侧操作数。

试一试

const foo = null ?? "default string";
console.log(foo);
// Expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// Expected output: 0

语法

js
leftExpr ?? rightExpr

描述

空值合并运算符可以看作是逻辑或 (||) 运算符的一种特殊情况。后者在左侧操作数为任何 假值时返回右侧操作数,而不仅仅是 nullundefined。换句话说,如果您使用 || 为另一个变量 foo 提供一些默认值,如果您认为某些假值是可用的(例如,''0),您可能会遇到意外行为。有关更多示例,请参阅下文

空值合并运算符的运算符优先级是第五低,直接低于 ||,直接高于条件(三元)运算符

不能将 AND (&&) 或 OR (||) 运算符直接与 ?? 组合使用。在这种情况下会抛出语法错误

js
null || undefined ?? "foo"; // raises a SyntaxError
true && undefined ?? "foo"; // raises a SyntaxError

相反,请提供括号以明确指示优先级

js
(null || undefined) ?? "foo"; // returns "foo"

示例

使用空值合并运算符

在此示例中,我们将提供默认值,但保留除了 nullundefined 之外的值。

js
const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;

const valA = nullValue ?? "default for A";
const valB = emptyText ?? "default for B";
const valC = someNumber ?? 0;

console.log(valA); // "default for A"
console.log(valB); // "" (as the empty string is not null or undefined)
console.log(valC); // 42

为变量赋值默认值

早些时候,当需要为变量赋值默认值时,一种常见的模式是使用逻辑或运算符 (||)

js
let foo;

// foo is never assigned any value so it is still undefined
const someDummyText = foo || "Hello!";

然而,由于 || 是一个布尔逻辑运算符,左侧操作数在评估时会被强制转换为布尔值,并且任何值(包括 0''NaNfalse 等)都不会被返回。如果您将 0''NaN 视为有效值,此行为可能会导致意外后果。

js
const count = 0;
const text = "";

const qty = count || 42;
const message = text || "hi!";
console.log(qty); // 42 and not 0
console.log(message); // "hi!" and not ""

空值合并运算符通过仅在第一个操作数评估为 nullundefined(但不包括其他假值)时返回第二个操作数来避免此陷阱

js
const myText = ""; // An empty string (which is also a falsy value)

const notFalsyText = myText || "Hello world";
console.log(notFalsyText); // Hello world

const preservingFalsy = myText ?? "Hi neighborhood";
console.log(preservingFalsy); // '' (as myText is neither undefined nor null)

短路求值

与“OR”和“AND”逻辑运算符一样,如果左侧表达式既不为 null 也不为 undefined,则右侧表达式不会被评估。

js
function a() {
  console.log("a was called");
  return undefined;
}
function b() {
  console.log("b was called");
  return false;
}
function c() {
  console.log("c was called");
  return "foo";
}

console.log(a() ?? c());
// Logs "a was called" then "c was called" and then "foo"
// as a() returned undefined so both expressions are evaluated

console.log(b() ?? c());
// Logs "b was called" then "false"
// as b() returned false (and not null or undefined), the right
// hand side expression was not evaluated

与可选链运算符 (?. ) 的关系

空值合并运算符将 undefinednull 视为特定值。 可选链运算符 (?.) 也如此,它对于访问可能为 nullundefined 的对象的属性很有用。将它们结合起来,您可以安全地访问可能为空值的对象的属性,并在其为空值时提供默认值。

js
const foo = { someFooProp: "hi" };

console.log(foo.someFooProp?.toUpperCase() ?? "not available"); // "HI"
console.log(foo.someBarProp?.toUpperCase() ?? "not available"); // "not available"

规范

规范
ECMAScript® 2026 语言规范
# prod-CoalesceExpression

浏览器兼容性

另见