Beginner JavaScript Interview QuestionsBeginnerConcept
JavaScript · Question 23
What is optional chaining (?.) in JavaScript, and when should you use it?
Direct answer
Optional chaining safely continues property access or optional calls only when the value on the left is not null or undefined; otherwise it returns undefined.
Without optional chaining, code often contains repeated existence checks before reading nested data. user?.address?.city returns undefined if user or address is nullish instead of throwing while trying to access the next property.
- Property access: obj?.property
- Computed access: obj?.[key]
- Optional call: callback?.()