Nikhil PC’s Post

Day 10: Optional Chaining & Null Safety — real bugs it prevents One of the most underrated features in TypeScript (and modern JavaScript) is optional chaining (?.). It looks small. But it saves you from some very real production bugs. 🚨 The Problem We’ve all written code like this: const userCity = user.address.city; Looks fine… until: ❌ user is null ❌ address is undefined ❌ API response changes 👉 Boom: "Cannot read property of undefined" 💡 The Fix — Optional Chaining const userCity = user?.address?.city; Now: ✅ No runtime crash ✅ Safely returns undefined ✅ Cleaner than multiple if checks 🧠 Real Bugs It Prevents ✔️ API responses missing fields ✔️ Optional form inputs ✔️ Feature flags not loaded ✔️ Nested config objects ✔️ User session data issues ⚡ Combine with Nullish Coalescing const city = user?.address?.city ?? "Unknown"; 👉 Default value only when null or undefined (not "" or 0) ❌ Without Optional Chaining if (user && user.address && user.address.city) { return user.address.city; } 👎 Verbose 👎 Hard to read 👎 Easy to miss a check 🎯 Key Takeaway Optional chaining is not just syntax sugar. It’s defensive programming built into the language. Less crashes. Cleaner code. Better developer sanity. 💬 Have you ever had a production bug because of undefined? Drop it below 👇 #TypeScript #JavaScript #WebDevelopment #Frontend #CleanCode #100DaysOfCode

  • graphical user interface

To view or add a comment, sign in

Explore content categories