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:

// If `dateOfBirth` is undefined, `birthYear` will be undefined as well
const birthYear = user.dateOfBirth?.year;
Copied to clipboard!

For full browser support, make sure you check the compatibility table on MDN.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
JavaScript Course

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.

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`
Copied to clipboard!
How to Use Optional Chaining in JavaScript
If you would like to see more Webtips, follow @flowforfrank


JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in 5 hours.

Learn More

πŸ“š Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. β˜•

Get access Support us
πŸŽ‰ Thank you for subscribing to our newsletter. x