JavaScript Runtime Semantics
Truthiness & Control Flow
JavaScript conditionals evaluate truthiness, not only booleans. This is convenient for presence checks, but dangerous when
0, false, or an empty string are valid values.- Falsy values are a small fixed set
- Truthiness is not the same as existence
??checks nullishness only||falls back for any falsy value- Control flow affects TypeScript narrowing
| Expression | Falls back when | Preserves 0/false/''? |
|---|---|---|
| value || fallback | Any falsy value | No |
| value ?? fallback | null or undefined | Yes |
| condition ? a : b | Explicit condition | Depends on condition |
function pageSize(input) {
return input || 20
}
pageSize(0) // 20, maybe wrong
function pageSizeSafe(input) {
return input ?? 20
}
pageSizeSafe(0) // 0