Nearby lessons

6 of 22

Advanced JavaScript: Optional Chaining (?.)

📌 What is Optional Chaining?

Optional chaining ?. is a feature in JavaScript that allows you to safely access deeply nested properties of an object without having to explicitly check if each reference in the chain is valid.

It prevents runtime errors caused by accessing properties of null or undefined.

1️⃣ Basic Syntax

Use ?. to access a property only if the preceding object is not null or undefined.

  • Safe way to access deeply nested object properties
  • Returns undefined instead of throwing an error if any part is null/undefined
  • Can be used with objects, arrays, and functions
Example02
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

2️⃣ Without Optional Chaining (Old Method)

Before optional chaining, developers had to use logical AND (&&) checks to access nested properties.

Example03
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

3️⃣ Optional Chaining with Arrays

You can use optional chaining to safely access elements of an array that might be null or undefined.

Example04
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

4️⃣ Optional Chaining with Functions

If a method or function might not exist, use optional chaining before calling it.

Example05
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3