Using logical nullish assignment in JavaScript (with examples)

Updated: February 19, 2024 By: Guest Contributor Post a comment

Overview

The concept of “nullish” values in JavaScript, which includes the values null and undefined, plays a crucial role in handling the absence of value in a more controlled manner. To augment this concept, ES2020 introduced the logical nullish assignment (??=) operator, which further streamlines how we deal with such values in our code. This tutorial endeavors to unpack the utility and application of this operator through practical examples.

Understanding the Basics

Before dissecting logical nullish assignments, let’s establish what nullish values entail. A nullish value in JavaScript is either null or undefined. These values denote the absence of a value or an uninitialized state. However, it’s critical to distinguish nullish values from other “falsy” values in JavaScript, such as false, 0, NaN, or the empty string (""), as each has different implications in conditional expressions and assignment operations.

The Logical Nullish Assignment operator (??=) allows for a more nuanced assignment. Instead of overwriting with a given value if the left-hand operand is merely “falsy” (as the logical OR assignment ||= would), ??= only assigns a value if the left-hand operand is strictly null or undefined. This specificity makes ??= particularly useful in numerous scenarios where a default value is needed only if one has not already been assigned.

Illustrative Examples

Let’s delve into practical examples to see the logical nullish assignment operator in action.

Example 1: Assigning Default Values

let userSettings = {
  theme: null
};

userSettings.theme ??= 'dark';
console.log(userSettings.theme);  // 'dark'

In this example, the theme property is initialized as null. Without directly checking if theme is nullish, ??= provides a neat one-liner to assign a default value (‘dark’). The operator ensures that the assignment only happens if theme is actually nullish.

Example 2: Avoiding Overwriting Non-nullish Values

let userPreferences = {
  notifications: false
};

userPreferences.notifications ??= true;
console.log(userPreferences.notifications);  // false

Here, despite false being a falsy value, the logical nullish assignment ensures that true is not assigned to notifications because false is not nullish. This distinction is particularly important in settings where a “falsy” value is a meaningful and valid choice, emphatically demonstrating the utility of ??= over other logical assignment operators like ||=.

Example 3: Nested Object Property Initialization

let config = {};

config.options ??= {};
config.options.setting ??= 'default';

console.log(config.options.setting);  // 'default'

This example showcases the logical nullish assignment’s aptitude for safely initializing nested object properties. It circumvents potential TypeError issues that might arise from attempting to access or assign properties of undefined.

Comparison with Other Operators

It’s instructive to compare ??= with similar JavaScript operators to grasp its unique standing.

Logical OR Assignment (||=): Assigns a value if the left-hand operand is falsy. Its broader condition for assignment makes ??= more precise for nullish checks since ??= focuses strictly on null or undefined.

Logical AND Assignment (&=): Whereas ??= and ||= deal with assignment, &= concerns itself with executing the right-hand side only if the left is truthy, which is a different context of use.

Final Words

To conclude, the logical nullish assignment operator ??= enriches the JavaScript language, providing a robust mechanism for handling nullish values. Its introduction marks a commitment to enhancing language semantics in ways that align closely with common programming scenarios, making code more intuitive and less prone to errors. Through understanding and effectively applying ??=, developers can write cleaner, more expressive, and more predictable JavaScript code.