The ??=
operator, also known as the logical nullish assignment operator, only evaluates the right operand and assigns to the left if the left operand is nullish (null
or undefined
).
The ??=
operator, also known as the logical nullish assignment operator, only evaluates the right operand and assigns to the left if the left operand is nullish (null
or undefined
).
Nullish coalescing assignment short-circuits, meaning that x ??= y
is equivalent to x ?? (x = y)
, except that the expression x
is only evaluated once.
No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x
being const
:
Neither would the following trigger the setter:
const x = { get value() { return 1; }, set value(v) { console.log("Setter called"); }, }; x.value ??= 2;
In fact, if x
is not nullish, y
is not evaluated at all.
You can use the nullish coalescing assignment operator to apply default values to object properties. Compared to using destructuring and default values, ??=
also applies the default value if the property has value null
.
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | Deno | Node.js | ||
Nullish_coalescing_assignment |
85 | 85 | 79 | 71 | 14 | 85 | 79 | 60 | 14 | 14.0 | 85 | 1.2 | 15.0.0 |
© 2005–2023 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/Nullish_coalescing_assignment