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

Chris Coyier Chris Coyier on

Nice reminder about JavaScript evolving to be more useful from Trevor I. Lasn:

// Old way (pre-2021)
if (user.name === null || user.name === undefined) {
  user.name = 'Anonymous';
}

// Or using the nullish coalescing operator (??)
user.name = user.name ?? 'Anonymous';

// New way (ES2021 and later)
user.name ??= 'Anonymous';Code language: JavaScript (javascript)

The final line there uses what is called the “The nullish coalescing assignment operator assignment operator” in case you need to impress people at parties.

It's time to take your JavaScript to the next level

Leave a Reply

Your email address will not be published. Required fields are marked *

$966,000

Frontend Masters donates to open source projects through thanks.dev and Open Collective, as well as donates to non-profits like The Last Mile, Annie Canons, and Vets Who Code.