Prevent JavaScript Runtime Crashes with Optional Chaining and Nullish Coalescing

Two JavaScript operators that quietly save you from runtime crashes: ?. — Optional Chaining ?? — Nullish Coalescing Before: const city = user.address.city; // 💥 Crashes if user or address is null After: const city = user?.address?.city ?? 'Unknown'; // ✅ Safe. Always. What each one does: ?. → Stops evaluation and returns undefined if anything in the chain is null/undefined. No crash, no if-checks needed. ?? → Returns the right-hand value ONLY when the left is null or undefined. Unlike ||, it won't replace 0, false, or '' — which are valid values. Combined, they make your data-fetching code 10x more resilient. One line. Zero crashes. Ship it. #JavaScript #WebDevelopment #Frontend #CodingTips #CleanCode

  • diagram

Nice tips! Also, `||` is best for strings or objects where an empty state should be replaced with a default value.

To view or add a comment, sign in

Explore content categories