Skip to content

Optional chaining in JS

Although it's currently in Stage 4, optional chaining is ready to go via Babel!

What even is "optional chaining", you ask?

Optional chaining allows you to access a property of an object (or an element of an array) without having to worry about getting a warning for a nullish value. It's especially useful the more nested within an object you need to access something.


Imagine you are loading some account info and you want to grab the username off of that account object. In the past, you would write something like this:

const username = data && data.account && data.account.username;

With optional chaining, we can declutter this code:

const username = data?.account?.username;

This code does the same thing. Is data nullish? If not, is the account nullish? If not, I'll take the username.


Additionally, you can utilize optional chaining when checking elements of an array:

const username = data && data.accounts && data.accounts[0] && data.accounts.[0].username;

Becomes:

const username = data?.accounts?.[0]?.username;

Wanna get better at working with arrays in JS? Check out my free course 🔥