Nullish coalescing
Learn to give a default for null and undefined with the ?? operator.
Nullish coalescing
The ?? operator (nullish coalescing) returns the right side only when the left side is null or undefined. Unlike ||, ?? does not replace valid falsy values like 0, "" or false.
Example: const count = userCount ?? 0;. If userCount is null, count becomes 0; but if userCount is 0, count stays 0. This is ideal when you do not want numbers or empty strings replaced by a default.
The difference between ?? and ||
Knowing the difference between ?? and || matters. || replaces all falsy values: 0 || 5 gives 5. But ?? replaces only null and undefined: 0 ?? 5 gives 0.
So when you want a default for a number, string or boolean variable, prefer ??. For example const discount = cartDiscount ?? 0; keeps 0 when cartDiscount is 0; with || the 0 would be lost. ?? distinguishes cases where the data is truly missing.
Exercise Default with ??
Set count to null. Set displayCount to count ?? 0. Print displayCount.
Show example solution
const count = null;
const displayCount = count ?? 0;
console.log(displayCount);
Exercise Show the ?? and || difference
Set value to 0. Set withOr to value || 100. Set withNullish to value ?? 100. Print both.
Show example solution
const value = 0;
const withOr = value || 100;
const withNullish = value ?? 100;
console.log(withOr);
console.log(withNullish);
Test yourself
-
What does 0 ?? 50 evaluate to?
0 ?? 50- null
- 50
- 0
- undefined
Show answer
0 — Correct. The ?? operator treats 0 as valid and returns 0.
-
Give a default with ??
const userCount = null; const count = userCount ____ 0; console.log(count);Show answer
const userCount = null; const count = userCount ?? 0; console.log(count);