In un contesto boolean (if, &&, ||, !), ogni valore viene trattato come truthy o falsy. Ci sono esattamente — tutto il resto è truthy.
In un contesto boolean (if, &&, ||, !), ogni valore viene trattato come truthy o falsy. Ci sono esattamente — tutto il resto è truthy.
I valori falsy: false, 0, -0, 0n (BigInt zero), "" (stringa vuota), null, undefined, NaN.
if ("") {} // 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.
Una raccolta di domande di colloquio IT con risposte dettagliate — da Junior a Senior.
Dona