The nullish coalescing assignment operator ??=
is relatively new to JavaScript. It was officially added in ECMAScript 2021 (ES12) as part of the βLogical Assignment Operatorsβ proposal.
Think of ??=
as a smart guardian for your variables. It only assigns a new value if the current one is null
or undefined
When you write something like user.name ??= 'Anonymous'
, the operator first checks if user.name
is null
or undefined
.
If it is null
or undefined
, only then does it assign 'Anonymous'
β If user.name
already has any other value - even an empty string or 0 - it stays untouched.
Why ??= Beats The Alternatives
Before ??=
, we had several ways to handle default values, but each had its drawbacks. Compare these approaches:
The ??
= operator gives us precision we didnβt have before. It only triggers when we truly have no value, making it perfect for cases where zero, empty strings, or false are valid data:
This precision helps prevent bugs that can occur when using broader checks. When building user interfaces or handling form data, you often want to preserve falsy values rather than replacing them with defaults.