JS-042

Beginner4 min~4 min read#optional-chaining#property-access#null
Optional Chaining ?.
Safe property access
Goal
Learn to safely access object properties using ?.
Explanation
- The ?. operator is called Optional Chaining.
- It lets you access properties safely.
- If the object exists, the property is read.
- If the object is null or undefined, no error is thrown.
- Instead of an error, it returns undefined.
Analogy
You want to look inside a box. If the box exists, you look inside. If it does not, you simply get the answer “there is nothing here” without a crash.
Code
let user = null;
console.log(user?.name);Result: undefined
Common mistake
Beginners access user.name even when user may be null. This causes an error. ?. solves this problem.
Remember
- ✦ ?. prevents property-access errors.
- ✦ If the object is missing, it returns undefined.
- ✦ ?. is often used when working with APIs and user data.
Quick Quiz
What does user?.name return when user = null?