JavaScript Course
JavaScript
/
Intermediate

Optional Chaining

Definition

The `?.` operator permits reading the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

Explain Like I'm New

Imagine trying to find a book in a library. Usually, if the library is closed, the program crashes with 'Cannot read properties of null'. Optional chaining says: 'Go into the library IF it's open, and find the book IF it exists. If anything is missing, just calmly return undefined instead of crashing.'

Real World Example

Safely reading data from an API response where nested objects might be missing: `const zip = user?.address?.zipCode;`

Common Use Cases

  • •Safe object traversal
  • •Calling callbacks safely `onSuccess?.()`

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What error does Optional Chaining prevent?

intermediate

  • Can you use Optional Chaining on array indexes?

advanced

  • Does Optional Chaining short-circuit the rest of the expression?

Flash Cards

Question

What error does it prevent?

Click to reveal answer
Answer

It prevents the dreaded `TypeError: Cannot read properties of undefined` which crashes the entire application.

Question

Does it short-circuit?

Click to reveal answer
Answer

Yes. If the left side of `?.` is null or undefined, the expression immediately stops evaluating and returns undefined. The right side is completely ignored.