WP 301 Redirects

In JavaScript, readability and concise syntax are vital for building maintainable and effective applications. One of the lesser-known but powerful features introduced in ES2020 is the double question mark operator (??), also known as the nullish coalescing operator. Understanding and appropriately using this operator allows developers to avoid common bugs related to falsy values and write cleaner code without sacrificing logic or consistency.

TL;DR

The nullish coalescing operator (??) is a safer, more intuitive alternative to the logical OR (||) when dealing with default values in JavaScript. It only returns the right-hand operand when the left-hand operand is null or undefined, not when it’s falsy (e.g., 0, "", or false). This distinction is crucial in applications where legitimate falsy values should be retained. Use ?? to guard against nullish values without accidentally overriding meaningful data.

What Is the Double Question Mark Operator?

The double question mark operator ??, also known as the nullish coalescing operator, is used to provide a default value when a variable is either null or undefined. This allows developers to avoid the pitfalls of defaulting values with ||, which treats all falsy values (like 0, empty string "", or false) as if they were “missing” or invalid, even when they may hold valid data.

Syntax:

let result = a ?? b;

This expression means “if a is not null or undefined, assign its value to result; otherwise, assign b.”

Why Not Just Use the Logical OR (||)?

The logical OR operator is often used to set default values. For instance:


let count = userInput || 10;

On the surface, this looks fine. But there’s a problem. If userInput is 0—a valid value in many contexts—the logical OR operator will treat it as falsy and assign 10 instead. This may lead to incorrect or unexpected behavior in your program.

With ??, only null or undefined are considered nullish, which means any valid falsy value like 0, false, or "" will be preserved.

Comparison of Behavior

Expression With || With ??
0 || 5 5 0
"" || "default" “default” “”
null || "fallback" “fallback” “fallback”
undefined || "fallback" “fallback” “fallback”

Real-World Use Cases

The nullish coalescing operator proves especially useful in the following scenarios:

  • Handling user input where a legitimate value of 0 or false should not be replaced by a default.
  • Working with configuration objects where missing keys should use a fallback, but present falsy values should remain untouched.
  • Rendering values in UI without accidentally overwriting valid data.

Here is an example involving configuration options:


const config = {
  darkMode: false,
  fontSize: 0,
  language: null
};

const userSettings = {
  darkMode: config.darkMode ?? true,       // false
  fontSize: config.fontSize ?? 16,         // 0
  language: config.language ?? 'en-US'     // 'en-US'
};

Notice how false and 0 are retained, but null is replaced.

Rules and Restrictions

Although ?? is straightforward to use, there are a few important rules to follow:

  1. Short-circuit behavior: Like ||, the expression on the right of ?? is only evaluated if the left is null or undefined.
  2. Cannot mix with || or && without parentheses: This results in a syntax error due to operator precedence and ambiguity.

Incorrect usage:


let result = input || defaultValue ?? fallbackValue; // SyntaxError

Correct usage:


let result = (input || defaultValue) ?? fallbackValue;

Understanding this restriction helps prevent unexpected behavior and syntax issues during runtime.

Null vs Undefined: The Subtle Difference

The nullish coalescing operator specifically caters to null and undefined, treating them as indicators of “no value.” It’s important to distinguish between these and other falsy values when designing application logic. While undefined often means “not assigned,” null is typically used to indicate the intentional absence of a value.

Image not found in postmeta
null apple

When You Should Not Use ??

Although powerful, the nullish coalescing operator isn’t always suitable. Avoid using it in these contexts:

  • When your default logic expects any falsy value to trigger a fallback (e.g., you want both 0 and null to result in a default).
  • When compatibility with older environments that don’t support ES2020 is necessary, unless you transpile your code using Babel or similar tools.

Combining with Optional Chaining (?.)

The ?? operator pairs well with optional chaining ?. by enabling both safe access to deeply nested object properties and defaulting when necessary. For instance:


const theme = settings?.preferences?.theme ?? 'light';

This protects the code from runtime errors if settings or preferences is undefined. If theme is null or undefined, it defaults to 'light'.

Browser Support and Compatibility

As of ES2020, most modern JavaScript environments support ?? natively. However, if your application must run in older browsers like Internet Explorer, you’ll need to transpile your code with a tool like Babel.

How to transpile:


npm install --save-dev @babel/plugin-proposal-nullish-coalescing-operator

And update your Babel configuration accordingly to include the plugin so your code works universally.

Conclusion

The JavaScript double question mark operator (??) is a powerful and precise tool for managing default values in variables. Unlike traditional defaults set with ||, it respects valid falsy values like false or 0, which makes it ideal for more nuanced logic and UI rendering. Taking the time to understand and properly implement this operator will improve the reliability and readability of your code across a range of applications.

Whether you’re building a frontend dashboard or a backend process, the nullish coalescing operator helps you avoid subtle bugs and clearly represent developer intent. As modern JavaScript evolves, mastering such