Wednesday, May 14, 2025

JavaScript latest updates: Cool stuff that you didn’t know that you can do with the web #3 | by Laura Morinigo | Samsung Internet Developers | Dec, 2024

Share

Logical assignment operators combine logical checks (||, &&, ??) with assignment, reducing verbosity and increasing readability. They allow you to handle defaults or conditional updates in fewer lines of code.

Code example:

Before

let options = { theme: null, language: 'en' };
// Manually checking and assigning defaults
if (!options.theme) {
options.theme = 'dark';
}
if (!options.language) {
options.language = 'en-US';
}
console.log(options);
// { theme: 'dark', language: 'en' }

After

let options = { theme: null, language: 'en' };// Logical OR assignment
options.theme ||= 'dark';
// Logical AND assignment
options.language &&= 'es';
// Nullish coalescing assignment
options.language ??= 'en-US';
console.log(options);
// { theme: 'dark', language: 'es' }

Let’s break these down further:

2.1 Logical Nullish Assignment (??=)

This is a sub-example of logical assignment operators and is particularly useful for setting a value only when it’s null or undefined.

Code example:

Before

let userPreference;
if (userPreference === null || userPreference === undefined) {
userPreference = 'light mode';
}
console.log(userPreference); // 'light mode'

After

let userPreference;
userPreference ??= 'light mode';
console.log(userPreference); // 'light mode'

This shorthand improves clarity and reduces boilerplate, making it a must-use for setting safe defaults.

Read more

Trending News