JavaScript Interview Question #93
What is optional chaining (?.)?
Promises, Async/Await, Fetch & Modern JavaScript Mid-Level Intermediate
Quick Interview Answer
Optional chaining safely accesses a property, element, or method when the value to the left may be null or undefined. If that value is nullish, evaluation stops and the expression returns undefined instead of throwing a property-access error.
Detailed Explanation
Optional chaining safely accesses a property, element, or method when the value to the left may be null or undefined. If that value is nullish, evaluation stops and the expression returns undefined instead of throwing a property-access error.
It is useful for genuinely optional relationships, but excessive optional chaining can hide incorrect assumptions when a value should actually be required.
Code Example
const user = {
profile: {
address: null
}
};
const city = user.profile?.address?.city;
console.log(city); // undefined