Example 1 — Compare with ||
|| treats all falsy values as missing.
JavaScript
console.log(0 || 10);
console.log(0 ?? 10); How It Works
- || replaces 0.
- ?? keeps 0.
The nullish coalescing operator ?? returns the right side only when the left side is null or undefined. Unlike ||, it keeps 0 and "".
console.log(0 ?? 10);
console.log("" ?? "x");
console.log(null ?? "x"); || treats all falsy values as missing.
console.log(0 || 10);
console.log(0 ?? 10); Common API pattern.
const cfg = {};
console.log(cfg.port ?? 3000); Both null and undefined.
console.log(undefined ?? "yes"); CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful