foundation
null vs undefined
Absence semantics, optional properties, defaulting, optional chaining, and nullish coalescing.
`undefined` usually means "not provided" or "property missing". `null` usually means deliberate absence. Both are nullish, but they signal different intent in APIs.
`value || fallback` treats every falsy value (0, "", false) as missing. `value ?? fallback` falls back only for `null` or `undefined`. Optional chaining `obj?.a?.b` short-circuits only where `?.` appears.
const count = 0;
console.log(count || 10); // 10 — wrong if 0 is valid
console.log(count ?? 10); // 0
Model API contracts explicitly: which fields are optional, which use null versus undefined, and whether 0 or false are valid states.
On interviews, explain the concept with a concrete example and name the runtime behavior interviewers probe.
Common pitfalls include mixing similar APIs and forgetting edge cases during live coding.
The trade-off is often clarity versus performance or safety versus convenience.
Checklist:
- Distinguish || from ??.
- Use ?. for guarded nested access.
- Document absence semantics in APIs.