Last modified: Jul 21, 2026

JS Nullish Coalescing Operator Guide

Dealing with missing data is a common task in JavaScript. The nullish coalescing operator (??) offers a clean solution. It helps you set default values for variables when they are null or undefined.

This operator is different from the logical OR (||). The OR operator treats many values as falsy. Nullish coalescing only reacts to two specific values. This makes your code more predictable.

What is the Nullish Coalescing Operator?

The nullish coalescing operator is ??. It returns the right-hand side value if the left-hand side is null or undefined. Otherwise, it returns the left-hand side.

Think of it as a safety net. It catches only the two specific "nullish" values. It ignores other falsy values like 0, "", or false.

This behavior is very useful for JavaScript Variable Typing Guide contexts. You can maintain a variable's type while providing a fallback.

Basic Syntax and Usage

The syntax is simple. Write the variable, then ??, then the default value.

 
// Basic example
let userName = null;
let displayName = userName ?? "Guest";
console.log(displayName); // Output: Guest

// With a defined value
let userAge = 25;
let age = userAge ?? 18;
console.log(age); // Output: 25

In the first example, userName is null. The operator returns "Guest". In the second, userAge is 25. It returns 25.

Nullish Coalescing vs. Logical OR

The logical OR operator (||) works differently. It returns the right-hand side for any falsy value. Falsy values include 0, "", false, NaN, null, and undefined.

Nullish coalescing only cares about null and undefined. This is a crucial difference for real-world data.

 
let score = 0;
let orResult = score || 100;  // Returns 100 because 0 is falsy
let nullishResult = score ?? 100; // Returns 0 because score is not null/undefined

console.log(orResult);      // Output: 100
console.log(nullishResult); // Output: 0

If you use || with a score of 0, you lose the real value. The nullish coalescing operator keeps the 0. This is perfect for numbers, empty strings, and boolean flags.

Using with Variables in Practice

You often load data from APIs or user input. These sources can be missing. Use ?? to set safe defaults for your Types of JavaScript Variables.

 
// Simulating API data
let apiResponse = {
    name: "Alice",
    age: null,
    preferences: {
        theme: ""
    }
};

// Setting defaults safely
let userName = apiResponse.name ?? "Anonymous";
let userAge = apiResponse.age ?? 30;
let theme = apiResponse.preferences.theme ?? "light";

console.log(userName); // Output: Alice
console.log(userAge);  // Output: 30
console.log(theme);    // Output: light (empty string is kept, then default applied)

Notice how the empty string "" for theme is kept. The operator does not treat it as nullish. This prevents accidental overwriting of valid falsy data.

Chaining with Optional Chaining

The nullish coalescing operator works well with optional chaining (?.). Optional chaining prevents errors when accessing nested properties that might be null or undefined.

 
let user = {
    profile: null
};

// Without optional chaining, this would throw an error
let city = user?.profile?.address?.city ?? "Unknown City";

console.log(city); // Output: Unknown City

This combination is powerful. It lets you safely traverse deep objects. If any part is missing, the fallback value is used. This is a best practice for JavaScript Variable Scope Explained patterns.

Assignment with Nullish Coalescing

There is a shorthand assignment operator: ??=. It assigns a value only if the variable is null or undefined.

 
let config = {
    timeout: null,
    retries: 3
};

config.timeout ??= 5000;  // Assigns 5000 because timeout is null
config.retries ??= 10;    // Does not assign because retries is 3

console.log(config.timeout); // Output: 5000
console.log(config.retries); // Output: 3

This is a concise way to set defaults without overwriting existing values. It makes your JavaScript Variable Declaration Guide cleaner and more intentional.

Common Mistakes to Avoid

Do not chain ?? with || or && without parentheses. JavaScript has specific operator precedence rules. This can lead to unexpected results.

 
// Wrong: This causes a syntax error
// let result = a ?? b || c;

// Correct: Use parentheses
let a = null;
let b = false;
let c = "default";
let result = (a ?? b) || c;
console.log(result); // Output: false (because (null ?? false) is false, and false || "default" is "default")

Always wrap the nullish coalescing part in parentheses when combining with other operators. This ensures the logic works as intended.

Real-World Example: User Settings

Imagine a settings panel. Users can leave fields empty. Use ?? to apply defaults while respecting their choices.

 
let userSettings = {
    fontSize: 0,
    darkMode: null,
    language: "en"
};

// Apply defaults only for null/undefined
let fontSize = userSettings.fontSize ?? 16;  // Keeps 0
let darkMode = userSettings.darkMode ?? false; // Sets false
let language = userSettings.language ?? "en"; // Keeps "en"

console.log(fontSize); // Output: 0
console.log(darkMode); // Output: false
console.log(language); // Output: "en"

The user explicitly set fontSize to 0. The operator respects that. It only fills in the darkMode setting.

Conclusion

The JavaScript nullish coalescing operator is a precise tool. It helps you write cleaner, safer code for handling variables that might be null or undefined. Unlike the logical OR, it does not mistake other falsy values for missing data.

Use ?? when you only want to provide a fallback for null or undefined. Combine it with optional chaining for deep object access. Use ??= for conditional assignment. This operator is now a standard part of modern JavaScript development.

Practice these examples. You will soon find yourself using nullish coalescing in your daily code. It will make your variable handling more robust and your intentions clearer.