← Back to JavaScript Course | Chapter 5: ES6+ Features | Lesson 5 of 12

JS Nullish Coalescing

Basic Nullish Coalescing

The ?? operator returns its right-hand value only when the left side is exactly null or undefined, leaving other falsy values like 0 or an empty string untouched. It was added specifically to fix a common bug with ||-based defaults.

Example: Basic Nullish Coalescing

javascript
const value = null ?? "default";
console.log(value);

Nullish vs OR

Unlike ||, which falls back on ANY falsy value, ?? only falls back on null/undefined. This matters when 0, NaN, or '' are legitimate values you don't want silently replaced by a default.

Example: Nullish vs OR

javascript
console.log(0 || "fallback"); // "fallback" - || treats 0 as falsy
console.log(0 ?? "fallback"); // 0 - ?? only checks null/undefined

False and Empty Strings

false, 0, and '' are falsy but not nullish, so ?? treats them as valid values and does not fall back. This is exactly the case where || used to misbehave and ?? was introduced to fix.

Example: False and Empty Strings

javascript
console.log(false ?? "x"); // false
console.log(0 ?? "x");     // 0
console.log("" ?? "x");    // ""

With Objects

?? works the same way when the left side is a property read off an object, making it a natural fit for reading optional config fields without accidentally overriding intentional falsy values.

Example: With Objects

javascript
const config = { timeout: 0 };
console.log(config.timeout ?? 5000); // 0, a real intentional value

With Optional Chaining

?? and ?. (optional chaining) are commonly combined: chain safely into a possibly-missing object, then supply a default only if the final result is null or undefined.

Example: With Optional Chaining

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

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.