Sentry Logo Debug Microservices & Distributed Systems

Join my free newsletter

Level up your dev skills and career with curated tips, practical advice, and in-depth tech insights – all delivered straight to your inbox.

3 min read
Up to date
intermediate

Trevor I. Lasn

Staff Software Engineer & Engineering Manager

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

A guide to using ??= in JavaScript to handle null and undefined values elegantly

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.


Become a better engineer

Here are engineering resources I've personally vetted and use. They focus on skills you'll actually need to build and scale real projects - the kind of experience that gets you hired or promoted.

Many companies have a fixed annual stipend per engineer (e.g. $2,000) for use towards learning resources. If your company offers this stipend, you can forward them your invoices directly for reimbursement.


This article was originally published on https://www.trevorlasn.com/blog/javascript-nullish-coalescing-assignment-operator. It was written by a human and polished using grammar tools for clarity.

Interested in a partnership? Shoot me an email at hi [at] trevorlasn.com with all relevant information.