Course contentsShow
← JavaScript
Lesson 1962 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

Combining with Optional Chaining

Using logical assignment operators together with optional chaining for safe, concise property initialization.

Combining with Optional Chaining

You'll learn how to use logical assignment operators together with optional chaining to safely initialize properties in nested objects without verbose null checks.

The Power of Two Modern Features Together

Optional chaining (?.) safely accesses nested properties that might not exist, while logical assignment operators (||=, &&=, ??=) conditionally assign values only when certain conditions are met. When combined, they create elegant patterns for property initialization that handle missing intermediate objects gracefully.

Safe Property Initialization

Imagine you need to initialize a property deep in an object structure, but the path to that property might not exist yet. Before these features, you'd write defensive code checking each level. Now you can combine them:

const user = {};

// Safely initialize a nested property
user.preferences ??= {};
user.preferences.theme ??= 'light';

// But what if the path is uncertain?
const settings = { user: null };

// This would throw without optional chaining:
// settings.user.preferences ??= {}; // Error!

// Combining both features:
settings.user?.preferences ??= {}; // Safe! Does nothing if user is null

The Pattern in Action

const config = { api: {} };

// Initialize nested config only if parent exists
config.api?.timeout ??= 5000;
config.database?.pool ??= 10; // Silent - database doesn't exist

console.log(config.api.timeout); // 5000
console.log(config.database); // undefined (not created)

The optional chaining prevents errors when the parent doesn't exist, while the logical assignment only sets values when the condition is right. Together, they short-circuit safely without throwing exceptions.

Key Takeaway: Combining optional chaining with logical assignment operators lets you safely initialize nested properties in one concise expression, gracefully handling missing intermediate objects without errors or verbose null checks.