In un contesto boolean (if, &&, ||, !), ogni valore viene trattato come truthy o falsy. Ci sono esattamente 8 valori falsy — tutto il resto è truthy.
I valori falsy: , , , (BigInt zero), (stringa vuota), , , .
In un contesto boolean (if, &&, ||, !), ogni valore viene trattato come truthy o falsy. Ci sono esattamente 8 valori falsy — tutto il resto è truthy.
I valori falsy: , , , (BigInt zero), (stringa vuota), , , .
false0-00n""nullundefinedNaNif ("") {} // skipped — empty string is falsy
if (0) {} // skipped
if ("0") {} // RUNS — non-empty string is truthy!
if ([]) {} // RUNS — empty array is truthy!
if ({}) {} // RUNS — empty object is truthy!
Le sorprese: "0", [], e {} sono tutti truthy, anche se sembrano "vuoti".
const name = input || "guest"; // ❌ if input is "" or 0, falls back to "guest"
const count = input ?? 0; // ✅ ?? only falls back on null/undefined
|| fallback per qualsiasi valore falsy, quindi un 0 o "" valido viene sostituito. L'operatore nullish coalescing ?? fallback solo per null/undefined, che è solitamente quello che vuoi davvero.
Conoscere il set falsy esatto previene i bug sottili — in particolare proteggere i numeri (if (count > 0) non if (count)) e scegliere ?? vs || per i valori predefiniti.