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
Code Example
PREVIEW READY
2๏ธโฃ Without Optional Chaining (Old Method)
Before optional chaining, developers had to use logical AND (&&) checks to access nested properties.
Code Example
PREVIEW READY
3๏ธโฃ Optional Chaining with Arrays
You can use optional chaining to safely access elements of an array that might be null or undefined.
Code Example
PREVIEW READY
4๏ธโฃ Optional Chaining with Functions
If a method or function might not exist, use optional chaining before calling it.
Code Example
PREVIEW READY
๐ง Test Your Knowledge
3 QuestionsProgress: 0 / 3
Keep Going!AJS - Nullish Coalescing