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

Frontend Masters logo

Frontend Masters is the best place on the web to really learn JavaScript. We have a complete learning path from the biggest and best teachers in JavaScript to help you make the most out of the web's biggest language.

7-Day Free Trial

Leave a Reply

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

$839,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.