Skip to content
Jonathan Speek

Optional Chaining in JS

JavaScript1 min read

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:

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

With optional chaining, we can declutter this code:

1const 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:

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

Becomes:

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