JavaScript Gotcha: 0 vs Nullish Coalescing

🚨 JavaScript Gotcha: When 0 Actually Matters One of the most subtle bugs in JavaScript comes from using the logical OR (||) for default values. const timeout = userTimeout || 3000; Looks fine… until userTimeout = 0. 👉 JavaScript treats 0 as falsy, so instead of respecting your value, it silently replaces it with 3000. 💥 Result? Unexpected behavior. ✅ The Fix: Use Nullish Coalescing (??) const timeout = userTimeout ?? 3000; This only falls back when the value is null or undefined — not when it’s 0. 💡 When does 0 actually matter? ⏱️ Timeouts & delays → 0 can mean run immediately 📊 Counters & stats → 0 is a valid value, not “missing” 💰 Pricing / discounts → Free (0) ≠ undefined 🎚️ Sliders / configs → Minimum values often start at 0 🧠 Rule of thumb: Use || when you want to catch all falsy values (0, "", false, etc.) Use ?? when you only want to catch missing values (null, undefined) ⚡ Small operator. Big difference. Cleaner logic. #reactjs,#nodejs #JavaScript #WebDevelopment #CleanCode #Frontend #ProgrammingTips #DevTips #CodeQuality #SoftwareEngineering

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories