In einem booleschen Kontext (if, &&, ||, !) wird jeder Wert als entweder truthy oder falsy behandelt. Es gibt genau 8 falsy Werte — alles andere ist truthy.
Die falsy Werte: , , , (BigInt Null), (leerer String), , , .
In einem booleschen Kontext (if, &&, ||, !) wird jeder Wert als entweder truthy oder falsy behandelt. Es gibt genau 8 falsy Werte — alles andere ist truthy.
Die falsy Werte: , , , (BigInt Null), (leerer String), , , .
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!
Die Überraschungen: "0", [] und {} sind alle truthy, obwohl sie sich "leer" anfühlen.
const name = input || "guest"; // ❌ if input is "" or 0, falls back to "guest"
const count = input ?? 0; // ✅ ?? only falls back on null/undefined
|| fällt bei jedem falsy Wert auf den Fallback zurück, sodass ein gültiges 0 oder "" ersetzt wird. Der Operator nullish coalescing ?? fällt nur bei null/undefined auf den Fallback zurück, was normalerweise das ist, was du eigentlich möchtest.
Zu wissen, welche exakten Werte falsy sind, verhindert subtile Fehler — besonders beim Schutz von Zahlen (if (count > 0) statt if (count)) und der Wahl zwischen ?? und || für Standard-Werte.