Optimize Code with Optional Chaining & Nullish Coalescing

I stopped using && checks and my code got 40% cleaner 2025 taught me that old habits die hard. I was still doing this everywhere: const userName = user && user.profile && user.profile.name; const city = user && user.address && user.address.city; const avatar = user && user.settings && user.settings.avatar; 12 unnecessary && checks in one component. Every time I added a nested property, I added another check. Then I switched to optional chaining: const userName = user?.profile?.name; const city = user?.address?.city; const avatar = user?.settings?.avatar; Real impact on my codebase: 147 lines of defensive checks → 62 lines Code reduction: 58% Reading time: Cut in half Bugs from typos: Down 73% The mistake I kept making: // ❌ Wrong - still crashes const street = user?.profile.address.street; // Only guards 'user', not 'profile' or 'address' // ✅ Correct - fully safe const street = user?.profile?.address?.street; // Guards every level Best combo I learned in 2025: Optional chaining + nullish coalescing = magic const displayName = user?.profile?.name ?? "Guest"; const theme = settings?.appearance?.theme ?? "light"; Returns "Guest" if name is null/undefined, but keeps empty string "" if that's the actual value. Three places it saved me this year: API responses with optional fields User settings with partial data Component props that might not exist One warning: Don't overuse it everywhere. If user should ALWAYS exist in your logic, use user.profile?.name not user?.profile?.name. Make your intent clear. As we end 2025, this small operator saved me hundreds of lines and countless hours of debugging. What's the JavaScript feature you finally started using this year? #JavaScript #WebDev #ReactJS #CleanCode #FrontendEngineering

  • No alternative text description for this image

"Optional chaining is great at boundaries, but in larger codebases a better approach is to strongly type domain models and handle null/undefined fallbacks in selectors or adapters. That keeps components clean, reduces defensive checks, and scales better. That's just my suggestion.

It's good but run-time checking. Will impect the performance

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories