How Optional Chaining (?.) Saves You from Runtime Errors

While working with JavaScript objects, we often access nested properties.
But what if one property doesn’t exist?

👉 That’s where optional chaining (?.) comes to the rescue.


❌ The Common Problem

Consider this example:

const user = {};
console.log(user.profile.name);

❌ This throws an error:

Cannot read properties of undefined

Why?
Because profile does not exist, and JavaScript tries to read name from undefined.


✅ The Solution: Optional Chaining (?.)

Now look at this:

const user = {};
console.log(user.profile?.name);

✅ Output:

undefined

No error.
The program continues smoothly.


What Does ?. Actually Do?

In very simple words:

If the value exists → access it
If it doesn’t → stop and return undefined

That’s it. No crash. No exception.


Very Simple Real-Life Analogy

Imagine asking someone:

“If you have my book, please give it.
If not, that’s okay.”

Optional chaining behaves the same way 😄


Simple API Response Example

const response = {
data: {
user: {
name: "Raj"
}
}
};
console.log(response.data?.user?.name); // Raj
console.log(response.data?.user?.age); // undefined

Instead of breaking the app, JavaScript safely returns undefined.


Before vs After Optional Chaining

❌ Old Way (Using &&)

const name = user && user.profile && user.profile.name;

✅ Modern Way (Optional Chaining)

const name = user.profile?.name;

✔ Cleaner
✔ Easier to read
✔ Less error-prone


⚠️ Important Things to Remember

  • Optional chaining only reads values
  • It does not create properties
  • It works only with:
    • Objects
    • Arrays
    • Functions

❌ This is invalid:

user.profile?.name = "Raj";

Optional Chaining with Arrays

const users = [];
console.log(users[0]?.name);

✅ Output:

undefined

No error even if the array is empty.


When Should You Use Optional Chaining?

✅ API responses
✅ Nested objects
✅ Data from backend
✅ Dynamic data

❌ When you are sure the value always exists


Interview One-Liner

Optional chaining (?.) allows safe access to nested properties without throwing errors when values are null or undefined.


Final Thoughts

Optional chaining may look small, but it prevents big runtime crashes.

One operator.
Cleaner code.
Fewer bugs.

That’s the power of ?.


If this post is helpful to you don’t forget to like and subscribe !!

One thought on “How Optional Chaining (?.) Saves You from Runtime Errors”

Leave a comment