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

JS Nullish Coalescing

Nullish coalescing gives you a backup value only when something is truly missing (null or undefined), like using a spare key only if you lost yours. Real values such as 0 are kept.
Syntax
javascript
const result = value ?? defaultValue;  // only for null or undefined

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.

उदाहरण: 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.

उदाहरण: 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.

उदाहरण: 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.

उदाहरण: 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.

उदाहरण: With Optional Chaining

javascript
const user = { address: null };
console.log(user?.address?.city ?? "Unknown");
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

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.