Hiprup

What is the difference between null coalescing (??) and logical OR (||)?

Both provide fallbacks, but trigger on different values.

  • || — falls back when the left side is any falsy value (0, "", false, null, undefined, NaN).

  • ?? — falls back only when the left side is null or undefined.

Use ?? when 0, "", or false are valid values you want to keep — || would wrongly replace them.

// || treats ALL falsy as 'missing'
console.log(0 || 10);       // 10 (WRONG if 0 is valid)
console.log('' || 'default'); // 'default' (WRONG if '' is valid)
console.log(false || true);  // true (WRONG if false is valid)

// ?? treats only null/undefined as 'missing'
console.log(0 ?? 10);       // 0 (CORRECT — 0 preserved)
console.log('' ?? 'default'); // '' (CORRECT — '' preserved)
console.log(false ?? true);  // false (CORRECT — false preserved)
console.log(null ?? 10);     // 10 (null triggers fallback)
console.log(undefined ?? 10); // 10 (undefined triggers fallback)

// Practical
const port = config.port ?? 3000;  // 0 is valid port!
const name = user.name ?? 'Guest'; // '' is valid name!
const count = data.count ?? 0;     // null/undefined → 0

|| replaces ALL falsy values. ?? replaces ONLY null and undefined. The port example: if config.port is 0, || gives 3000 (wrong), ?? gives 0 (correct).

Use ?? for defaults where 0, '', and false are valid values.

?? = null/undefined only. || = all falsy (0, '', false, null, undefined, NaN). The 0 and '' examples are the key — ?? preserves them, || replaces them.

Always use ?? for defaults in modern code (unless you intentionally want to replace all falsy values).

What is the difference between null coalescing (??) and logical OR (||)? | Hiprup