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

Chaining Nullish Coalescing

Use multiple ?? operators in sequence to create fallback chains for nested defaults.

Chaining Nullish Coalescing

What you'll learn: How to use multiple ?? operators in sequence to create elegant fallback chains when you need several layers of default values.

The Core Idea

Just like you can chain optional chaining (?.), you can chain multiple nullish coalescing operators (??) together to create a prioritized list of fallback values. The expression evaluates left-to-right, returning the first value that isn't null or undefined.

Think of it like a waterfall: water flows to the first level that can catch it. If the first variable is nullish, check the second. If that's nullish too, check the third, and so on.

How It Works

let primary = null;
let secondary = undefined;
let tertiary = 'fallback';

let result = primary ?? secondary ?? tertiary;
console.log(result); // 'fallback'

The expression primary ?? secondary ?? tertiary checks each value in order and returns the first non-nullish value it finds.

Real-World Example

This is incredibly useful for configuration objects with multiple fallback sources:

function getConfig(userConfig, envConfig, defaultConfig) {
  return {
    timeout: userConfig.timeout ?? envConfig.timeout ?? defaultConfig.timeout,
    retries: userConfig.retries ?? envConfig.retries ?? defaultConfig.retries
  };
}

let config = getConfig(
  { timeout: null }, 
  { timeout: undefined, retries: 3 }, 
  { timeout: 5000, retries: 1 }
);

console.log(config.timeout); // 5000 (from defaultConfig)
console.log(config.retries); // 3 (from envConfig)

Notice how each chain stops at the first defined value, creating a clear priority hierarchy: user settings → environment settings → defaults.

Key Takeaway: Chaining ?? operators creates readable fallback chains that check multiple sources in priority order, returning the first non-nullish value without the pitfalls of falsy value coercion.