एक boolean context में (if, &&, ||, !), प्रत्येक मान को truthy या falsy के रूप में माना जाता है। बिल्कुल 8 falsy values हैं — बाकी सब कुछ truthy है।
Falsy values: , , , (BigInt शून्य), (खाली string), , , ।
एक boolean context में (if, &&, ||, !), प्रत्येक मान को truthy या falsy के रूप में माना जाता है। बिल्कुल 8 falsy values हैं — बाकी सब कुछ truthy है।
Falsy values: , , , (BigInt शून्य), (खाली 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!
आश्चर्य: "0", [], और {} सभी truthy हैं, भले ही वे "खाली" लगते हों।
const name = input || "guest"; // ❌ if input is "" or 0, falls back to "guest"
const count = input ?? 0; // ✅ ?? only falls back on null/undefined
|| किसी भी falsy मान के लिए वापस गिरता है, इसलिए एक वैध 0 या "" बदल दिया जाता है। nullish coalescing operator ?? केवल null/undefined के लिए वापस गिरता है, जो आमतौर पर आप वास्तव में चाहते हैं।
सटीक falsy set को जानना सूक्ष्म bugs को रोकता है — विशेष रूप से संख्याओं की सुरक्षा (if (count > 0) नहीं if (count)) और defaults के लिए ?? बनाम || चुनना।