Master Optional Chaining and Nullish Coalescing in JavaScript

This article explains how JavaScript's optional chaining (?.) and nullish coalescing (??) operators simplify safe access to nested object properties and provide reliable default values, replacing older verbose patterns with concise, readable code.

JavaScript
JavaScript
JavaScript
Master Optional Chaining and Nullish Coalescing in JavaScript

Before optional chaining and nullish coalescing were added to JavaScript, developers had to combine several techniques to safely access nested object properties and handle null or undefined values. Those methods worked but were cumbersome.

1. Using Logical AND (&&)

Early code often checked a property with logical AND: var value = obj && obj.prop; This works for a single level but becomes unreadable for deep nesting.

2. Using Logical OR (||) for defaults

To provide a fallback when a variable might be null or undefined, developers used the OR operator: var value = obj && obj.prop || defaultValue; However, this also treats other falsy values ( false, 0, '') as missing, which can lead to unexpected behavior.

3. Nested Checks

For deeper structures, multiple checks were chained:

var value = obj && obj.level1 && obj.level1.level2 && obj.level1.level2.level3;

While functional, the code is verbose, hard to read, and error‑prone.

What Is the Optional Chaining Operator (?.)

Basic Concept

The optional chaining operator ( ?.) simplifies accessing a property or calling a function on an object that might be null or undefined. If the left‑hand side is null or undefined, the whole expression evaluates to undefined without throwing an error.

Usage Example

const user = {
    address: {
        city: "Beijing"
    }
};
console.log(user.address?.city); // "Beijing"
console.log(user.unknown?.city); // undefined

How It Works

When the operand before ?. is null or undefined, the expression short‑circuits to undefined and no further property access occurs.

console.log(null?.prop); // undefined
console.log(undefined?.prop); // undefined

What Is the Nullish Coalescing Operator (??)

Basic Concept

The nullish coalescing operator ( ??) returns the right‑hand operand only when the left‑hand operand is null or undefined. Unlike ||, it does not treat other falsy values as missing.

Usage Example

let name = null;
const defaultName = "Guest";
console.log(name ?? defaultName); // "Guest"

How It Works

If the left side is null or undefined, ?? yields the right side; otherwise it returns the left side unchanged.

console.log(null ?? "default"); // "default"
console.log(undefined ?? "default"); // "default"
console.log("Hello" ?? "default"); // "Hello"

Combining Both Operators

In real projects, optional chaining and nullish coalescing are often used together to safely retrieve deep values and provide defaults.

const user = {
    address: {
        city: null
    }
};
const cityName = user.address?.city ?? "Unknown City";
console.log(cityName); // "Unknown City"

This combination first checks whether user.address.city exists; if it does not, ?? supplies a fallback, preventing undefined from propagating.

By leveraging these ES2020 operators, developers can write cleaner, more maintainable code when dealing with potentially missing data.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendJavaScriptCode Examplesoptional chainingES2020nullish coalescing
JavaScript
Written by

JavaScript

Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.