While polishing my JavaScript skills, I recently learned about the Optional Chaining operator (?.
).
It’s a small feature, but it can save us from big headaches. Let me share what I learned 👇
🔎 The Problem Without Optional Chaining
Imagine you’re working with nested objects. Normally, if you try to access a property that doesn’t exist, JavaScript will throw an error.
const user = {
contact: {
email: "test@example.com",
},
};
console.log(user.profile.age); // ❌ Error: Cannot read properties of undefined
Here, because profile
doesn’t exist, the code crashes.
âś… The Optional Chaining Solution
With the ?.
operator, we can safely check whether a property exists before trying to access it:
const user = {
contact: {
email: "test@example.com",
},
};
console.log(user?.contact?.email); // "test@example.com"
console.log(user?.profile?.age); // undefined (no error!)
Instead of throwing an error, JavaScript just returns undefined
.
💡 Why It’s Useful
- Prevents runtime errors
- Makes code cleaner (no need for multiple
if
checks) - Super helpful when dealing with deeply nested objects or API responses
🌱 Final Thought
The Optional Chaining operator (?.
) may look like a tiny piece of syntax, but it’s a big productivity booster.
It’s another handy tool I’ve added to my JavaScript toolbox as I continue my learning journey. 🚀
Top comments (1)
Very well explained!👏🏻 Good work!