Use Optional Chaining (`?.`) Safely in JavaScript
Optional chaining (?.) lets JavaScript stop a property-access chain when the value immediately before ?. is null or undefined. Instead of throwing, the expression evaluates to undefined.
Nested Properties
const user = {
profile: {
name: 'Alice',
address: { city: 'Wonderland' },
},
};
const city = user.profile?.address?.city;
const postalCode = user.profile?.address?.postalCode;postalCode is undefined rather than causing an error.
Dynamic Property Access
const key = 'name';
const name = user.profile?.[key];Optional Method Calls
const name = user.profile?.getName?.();If getName is null or undefined, the result is undefined. If it exists but is not callable, JavaScript still throws a TypeError.
Arrays
const users = [{ name: 'Alice' }, { name: 'Bob' }];
const second = users?.[1]?.name; // Bob
const third = users?.[2]?.name; // undefined
Combine with ??
const displayName = user.profile?.name ?? 'Guest';This is a common pattern for reading optional data and supplying a fallback.
Do Not Hide Required Data Problems
Optional chaining is useful when absence is expected. If a property is required by your application contract, silently converting a missing value to undefined can hide a bug. Validate required data explicitly.
Conclusion
Use ?. for genuinely optional object paths, dynamic properties, array elements, and methods. Combine it with ?? for defaults, but do not use it to avoid validating data that should always exist.