Optional Chaining & Nullish Coalescing in JavaScript

🧠 Day 24 — Optional Chaining (?.) & Nullish Coalescing (??) Tired of errors like “Cannot read property of undefined”? 🤔 These two operators will save you 🚀 --- ⚡ 1. Optional Chaining ?. 👉 Safely access nested properties const user = { profile: { name: "John" } }; console.log(user.profile?.name); // John console.log(user.address?.city); // undefined (no error) 👉 Stops execution if value is null or undefined --- ⚡ 2. Nullish Coalescing ?? 👉 Provides a default value only if value is null or undefined const name = null; console.log(name ?? "Guest"); // Guest --- ⚠️ Difference from || console.log(0 || "Default"); // "Default" ❌ console.log(0 ?? "Default"); // 0 ✅ 👉 || treats falsy values (0, "", false) as false 👉 ?? only checks null or undefined --- 🚀 Why it matters ✔ Prevents runtime errors ✔ Cleaner and safer code ✔ Widely used in APIs & React apps --- 💡 One-line takeaway: 👉 “Use ?. to safely access, ?? to safely default.” --- Once you start using these, your code becomes much more robust. #JavaScript #ES6 #OptionalChaining #WebDevelopment #Frontend #100DaysOfCode 🚀

To view or add a comment, sign in

Explore content categories