When to Chain

While the optional chaining operator (?.) is an excellent tool for preventing runtime crashes, you should not use it everywhere by default.

The Golden Rule of Chaining

You should only use ?. when you expect that an object might legitimately not exist according to your business logic.

If your application strictly requires an object to be there, and it is missing, you want it to throw an error. Errors expose bugs so they can be fixed; hiding them makes debugging nearly impossible.

Bad Practice (Overusing)

Imagine a scenario where every user in your database must have an address object, but that address might optionally be missing a street name.

// BAD: We expect 'address' to always exist, so hiding a missing address object hides a massive data corruption bug!
const street = user?.address?.street;

Good Practice (Targeted Usage)

If address is strictly guaranteed, but street is optional, use standard dot notation up until the point of uncertainty.

// GOOD: If 'address' is missing, it crashes immediately (exposing the bug).
// If 'address' exists but 'street' is missing, it safely returns undefined.
const street = user.address?.street;

Remember: Good errors make debugging easier. Don’t suppress them unless you explicitly intend to handle the absence of that data gracefully.