The nullish coalescing assignment operator ??= is relatively new to JavaScript. It was officially added in ECMAScript 2021 (ES12) as part of the “Lo

JavaScript's ??= Operator: Default Values Made Simple

submited by
Style Pass
2024-11-05 17:30:09

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.

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.

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.

Leave a Comment