3 min read
•Question 24 of 50easyWhat is Optional Chaining in JavaScript?
Understanding the ?. operator.
What You'll Learn
- Optional chaining syntax
- Use cases
- Combining with nullish coalescing
Optional Chaining (?.)
Safely access nested properties without checking each level.
code.jsJavaScript
const user = {
name: 'John',
address: {
city: 'NYC'
}
};
// Without optional chaining
const zip = user && user.address && user.address.zip;
// With optional chaining
const zip = user?.address?.zip; // undefined (not error)Use Cases
code.jsJavaScript
// Object properties
const city = user?.address?.city;
// Array elements
const first = arr?.[0];
// Method calls
const result = obj?.method?.();
// Dynamic properties
const prop = obj?.[dynamicKey];With Nullish Coalescing
code.jsJavaScript
const city = user?.address?.city ?? 'Unknown';
// API response handling
const data = response?.data?.users ?? [];Function Arguments
code.jsJavaScript
function getFullName(user) {
return `${user?.firstName ?? ''} ${user?.lastName ?? ''}`.trim();
}
getFullName(null); // ''
getFullName({}); // ''
getFullName({ firstName: 'John' }); // 'John'