Nearby lessons
6 of 22Advanced 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
undefinedinstead of throwing an error if any part isnull/undefined - Can be used with objects, arrays, and functions
Example02
2️⃣ Without Optional Chaining (Old Method)
Before optional chaining, developers had to use logical AND (&&) checks to access nested properties.
Example03
3️⃣ Optional Chaining with Arrays
You can use optional chaining to safely access elements of an array that might be null or undefined.
Example04
4️⃣ Optional Chaining with Functions
If a method or function might not exist, use optional chaining before calling it.
Example05
🧠 Test Your Knowledge
3 QuestionsProgress: 0 / 3