Door 08 | JS Adventskalender
Skip to content

Door 08

Published: at 07:00 AMSuggest Changes

Nullish Coalescing – Handling null and undefined

In the JavaScript universe, null and undefined are ubiquitous values that can often lead to unexpected behavior if not handled properly. With the introduction of the Nullish Coalescing Operator (??) in ES2020, JavaScript has received a powerful tool to elegantly deal with null and undefined. In this article, we will explain how the Nullish Coalescing Operator works and how it differs from other operators like the logical OR ||.

The Problem with Falsy Values

In JavaScript, the following values are considered “falsy”:

When handling default values, the logical OR operator || was traditionally used:

const value = userInput || 'Default value';

The problem here is that 0, empty strings, or false are also considered falsy, so the default value is used even when this is not desired.

Example:

const userCount = 0;
const totalUsers = userCount || 100;

console.log(totalUsers); // Output: 100

In this case, we actually want to keep 0, but due to the || operator, 100 is assigned.

Introduction of the Nullish Coalescing Operator (??)

The Nullish Coalescing Operator ?? explicitly checks for null or undefined and not for other falsy values. It returns the right operand only if the left operand is null or undefined.

Syntax:

const value = expression1 ?? expression2;

Examples of Application

Let’s look at some simple examples of using Nullish Coalescing.

1. Handling null and undefined:

const userName = null;
const displayName = userName ?? 'Guest';

console.log(displayName); // Output: 'Guest'

Since userName is null, 'Guest' is used.

2. Keeping Falsy Values Except null and undefined:

const userCount = 0;
const totalUsers = userCount ?? 100;

console.log(totalUsers); // Output: 0

Here, userCount is preserved because 0 is not null or undefined.

3. Comparison with the Logical OR ||:

const userInput = '';
const data = userInput || 'Default value';

console.log(data); // Output: 'Default value'

const dataCorrect = userInput ?? 'Default value';

console.log(dataCorrect); // Output: ''

With ||, the empty string is overwritten, while ?? keeps the empty string.

Combination with Optional Chaining

The Nullish Coalescing Operator can be effectively combined with the Optional Chaining Operator ?. to safely access nested properties and set default values when needed.

As we learned on Day 7, the Nullish Coalescing Operator works very well together with the Optional Chaining Operator.

Example:

const user = {
  profile: {
    email: 'user@example.com'
  }
};

const phoneNumber = user.profile?.phoneNumber ?? 'No phone number available';

console.log(phoneNumber); // Output: 'No phone number available'

If user.profile or user.profile.phoneNumber is undefined, the default value is used.

Limitations and Operator Precedence

It is important to note that the Nullish Coalescing Operator ?? cannot be combined with the logical AND && or the logical OR || without parentheses, as this leads to syntax errors.

Wrong:

const result = a || b ?? c; // SyntaxError

Correct:

const result = (a || b) ?? c;

Or better, don’t mix the operators and instead design the logic accordingly.

Practical Use Cases

To conclude, here are some simple practical use cases for using the Nullish Coalescing Operator.

1. Default Values for Function Parameters:

function greet(name) {
  const displayName = name ?? 'Guest';
  console.log(`Hello, ${displayName}!`);
}

greet(); // Output: 'Hello, Guest!'
greet('Anna'); // Output: 'Hello, Anna!'

2. Configuration Settings with Default Values:

const config = {
  timeout: 0,
  theme: null
};

const timeoutValue = config.timeout ?? 5000;
const themeValue = config.theme ?? 'light';

console.log(timeoutValue); // Output: 0
console.log(themeValue);   // Output: 'light'

3. Handling API Data:

When working with data from APIs that may contain null or undefined, ?? can help safely set default values.

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    const items = data.items ?? [];
    // Further processing of items
  });

Conclusion

The Nullish Coalescing Operator ?? is a valuable tool for easily dealing with null and undefined without unintentionally overwriting other falsy values. It improves code readability and maintainability by signaling clear intentions and avoiding common pitfalls.

Use the Nullish Coalescing Operator in your next project and simplify handling null and undefined in your JavaScript code!


Previous Post
Door 09
Next Post
Door 07