逻辑空赋值(??=)

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020.

逻辑空赋值运算符(x ??= y)仅在 x空值nullundefined)时对其赋值。

尝试一下

const a = { duration: 50 };

a.speed ??= 25;
console.log(a.speed);
// Expected output: 25

a.duration ??= 10;
console.log(a.duration);
// Expected output: 50

语法

js
expr1 ??= expr2

描述

短路评估

空值合并运算符从左至右求值,其使用以下规则测试是否可能进行语法短路求值:

(结果非 null 或 undefined 的表达式) ?? expr 被短路求值为左侧表达式,当左侧证明为既非 null 也非 undefined.

语法短路意味着 expr 部分尚未被求值,因此任何与其求值产生的相关副作用都不会生效(例如,如果 expr 是一个函数调用,则该调用将不会发生)。

逻辑空赋值的语法短路也意味着 x ??= y 等价于:

js
x ?? (x = y);

而不等价于如下的表达式,因为其一定会发生赋值:

js
x = x ?? y;

示例

使用逻辑空赋值

js
function config(options) {
  options.duration ??= 100;
  options.speed ??= 25;
  return options;
}

config({ duration: 125 }); // { duration: 125, speed: 25 }
config({}); // { duration: 100, speed: 25 }

规范

Specification
ECMAScript® 2025 Language Specification
# sec-assignment-operators

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
Nullish coalescing assignment (x ??= y)

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见