Em um contexto booleano (um if, &&, ||, !), cada valor é tratado como truthy ou falsy. Existem exatamente 8 valores falsy — tudo o resto é truthy.
Os valores falsy: , , , (BigInt zero), (string vazia), , , .
Em um contexto booleano (um if, &&, ||, !), cada valor é tratado como truthy ou falsy. Existem exatamente 8 valores falsy — tudo o resto é truthy.
Os valores falsy: , , , (BigInt zero), (string vazia), , , .
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!
As surpresas: "0", [] e {} são todos truthy, mesmo que pareçam "vazios".
const name = input || "guest"; // ❌ if input is "" or 0, falls back to "guest"
const count = input ?? 0; // ✅ ?? only falls back on null/undefined
O || retorna para qualquer valor falsy, então um 0 ou "" válido é substituído. O operador nullish coalescing ?? retorna apenas para null/undefined, que é geralmente o que você realmente quer.
Conhecer o conjunto exato de falsy previne bugs sutis — especialmente proteger números (if (count > 0) não if (count)) e escolher ?? versus || para valores padrão.