Null 合体代入 (??=)

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.

Null 合体代入 (x ??= y) 演算子は、xnullish (null または undefined) である場合にのみ代入を行います。

試してみましょう

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 合体演算子は左から右に評価され、次のルールを使って短絡評価の可能性があるかどうかテストされます。

(null や undefined ではない式) ?? expr は、左辺が null でも undefined でもないことが証明されたら、左辺の式が短絡評価されます。

短絡評価とは、上記の expr 部分が評価されないことを意味します。したがって、評価された場合の副作用は発生しません (例えば、expr が関数呼び出しである場合、呼び出しは行われません)。

Null 合体代入も短絡評価されます。これは、x ??= y が以下と等価であることを意味します。

js
x ?? (x = y);

そして、常に代入が行われる以下と等価ではありません。

js
x = x ?? y;

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 }

仕様書

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

関連情報