
How to Use Optional Chaining in JavaScript
Optional chaining is coming to JavaScript. It lets you access deeply nested properties without having to explicitly check each object for its existence.
Instead of getting the famous βcannot read property of undefined
β error message, the expression short circuits with undefined.
To use it, simply mark optional properties with a question mark:
Copied to clipboard!
// If `dateOfBirth` is undefined, `birthYear` will be undefined as well
const birthYear = user.dateOfBirth?.year;
For full browser support, make sure you check the compatibility table on MDN.
Do You Need a Fallback Option?
If you rather want to use a more compatible version, you can achieve the same thing using a reduce
function.
Copied to clipboard! Playground
const getProperty = (obj, path) => (path.split('.').reduce((value, el) => value[el], obj));
const user = {
settings: {
theme: 'default'
}
};
getProperty(user, 'settings.theme'); // This will return βdefaultβ
getProperty(user, 'settings.invalidPath'); // This will return `undefined`

Resource
π More Webtips
Master the Art of Frontend
Access exclusive interactive lessons
Unlimited access to hundreds of tutorials
Remove ads to learn without distractions