How to Use Optional Chaining in JavaScript

How to Use Optional Chaining in JavaScript

Ferenc Almasi β€’ 2020 August 05 β€’ Read time 1 min read
  • twitter
  • facebook
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;
optional-chaining.js

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`
optiona-chaining.js
How to Use Optional Chaining in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Resource

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.