Null 合体代入 (x ??= y
) 演算子は、x
が nullish (null
または undefined
) である場合にのみ代入を行います。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
構文
expr1 ??= expr2
説明
短絡評価(ショートサーキット)
Null 合体演算子は左から右に評価され、次のルールを使って短絡評価の可能性があるかどうかテストされます。
(null や undefined ではない式) ?? expr
は、左辺が null
でも undefined
でもないことが証明されたら、左辺の式が短絡評価されます。
短絡評価とは、上記の expr
部分が評価されないことを意味します。したがって、評価された場合の副作用は発生しません。(例えば、expr
が関数呼び出しである場合、呼び出しは行われません。)
Null 合体代入も短絡評価されます。これは、x ??= y
が以下と等価であることを意味します。
x ?? (x = y);
そして、常に代入が行われる以下と等価ではありません。
x = x ?? y;
例
Null 合体代入演算子の使用
function config(options) {
options.duration ??= 100;
options.speed ??= 25;
return options;
}
config({ duration: 125 }); // { duration: 125, speed: 25 }
config({}); // { duration: 100, speed: 25 }
仕様
ブラウザの互換性
BCD tables only load in the browser
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.