空值合併賦值 (??=)

Baseline 已廣泛支援

此功能已成熟,並可在許多裝置和瀏覽器版本上使用。自 2020 年 9 月起,所有瀏覽器均已提供此功能。

空值合併賦值 (??=) 運算子,也稱為邏輯空值賦值運算子,僅當左側運算元為空值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
x ??= y

描述

空值合併賦值具有短路特性,這意味著 x ??= y 等同於 x ?? (x = y),不同之處在於表示式 x 只會評估一次。

如果左側不為空值,則由於空值合併運算子的短路特性,不會執行賦值。例如,以下程式碼不會丟擲錯誤,即使 xconst

js
const x = 1;
x ??= 2;

以下程式碼也不會觸發 setter

js
const x = {
  get value() {
    return 1;
  },
  set value(v) {
    console.log("Setter called");
  },
};

x.value ??= 2;

事實上,如果 x 不為空值,則根本不會評估 y

js
const x = 1;
x ??= console.log("y evaluated");
// Logs nothing

示例

使用空值合併賦值

您可以使用空值合併賦值運算子為物件屬性應用預設值。與使用解構和預設值相比,如果屬性的值為 null??= 也會應用預設值。

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

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

規範

規範
ECMAScript® 2026 語言規範
# sec-assignment-operators

瀏覽器相容性

另見