Sub topic 1
What Counts as Nullish
Prerequisites
This chapter assumes you know JavaScript variables, objects and arrays, dot and bracket property access, and how to call functions. It also assumes you know truthy and falsy values and how || and && behave.
Nullish Versus Falsy
A value is nullish if it is null or undefined. Nothing else is nullish.
A falsy value is any value that becomes false in a boolean context. Falsy values form a larger set: false, 0, -0, 0n, "", NaN, null and undefined. Every nullish value is falsy, but 0, "" and false are falsy without being nullish. They are real data. They do not mean the value is missing.
| Value | Falsy? | Nullish? |
|---|---|---|
| `null` | yes | yes |
| `undefined` | yes | yes |
| `0`, `""`, `false`, `NaN` | yes | no |
| `"0"`, `[]`, `{}` | no | no |
Why || Gets Defaults Wrong
a || b returns b whenever a is falsy. That means a volume of 0 or an empty title gets replaced with the default, even though the user chose it on purpose.
Precise Defaults with ??
The nullish coalescing operator a ?? b returns b only when a is null or undefined. Any other value, falsy or not, is kept.
const settings = { volume: 0, title: "" };
console.log(settings.volume || 50); // 50 (0 is falsy, so it is replaced)
console.log(settings.volume ?? 50); // 0 (0 is not nullish, so it is kept)
console.log(settings.title ?? "Untitled"); // ""
console.log(settings.missing ?? "fallback"); // "fallback"Use ?? when 0, "" or false are valid values. Use || only when you really want every falsy value replaced.
Safe Property Access with ?.
The optional chaining operator obj?.prop reads prop when obj is not nullish. When obj is null or undefined, it returns undefined and does not throw an error.
const user = { profile: null };
console.log(user.profile?.name); // undefined
// console.log(user.profile.name); // TypeError: Cannot read properties of nullThe check applies only to the value directly to the left of ?.. In user.profile?.name, user itself must still exist.
Exercise
Given const cfg = { retries: 0 }, what do cfg.retries || 3, cfg.retries ?? 3 and cfg.limits?.max ?? 10 evaluate to?
Show answer
cfg.retries || 3 is 3 because 0 is falsy. cfg.retries ?? 3 is 0 because 0 is not nullish. cfg.limits?.max ?? 10 is 10: cfg.limits is undefined, so ?. returns undefined, and ?? then supplies 10.