The logical nullish assignment (x ??= y) operator only assigns if x is nullish (null or undefined).
The logical nullish assignment (x ??= y) operator only assigns if x is nullish (null or undefined).
expr1 ??= expr2
The nullish coalescing operator is evaluated left to right, it is tested for possible short-circuit evaluation using the following rule:
(some expression that is neither null nor undefined) ?? expr is short-circuit evaluated to the left-hand side expression if the left-hand side proves to be neither null nor undefined.
Short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place).
Logical nullish assignment short-circuits as well meaning that x ??= y is equivalent to:
x ?? (x = y);
And not equivalent to the following which would always perform an assignment:
x = x ?? y;
function config(options) { options.duration ??= 100; options.speed ??= 25; return options; } config({ duration: 125 }); // { duration: 125, speed: 25 } config({}); // { duration: 100, speed: 25 }
| Desktop | Mobile | Server | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js | |
Logical_nullish_assignment |
85 |
85 |
79 |
No |
71 |
14 |
85 |
85 |
79 |
60 |
14 |
14.0 |
1.2 |
15.0.0 |
© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment