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
Additionally, you can utilize optional chaining when checking elements of an array:
1const username = data && data.accounts && data.accounts && data.accounts..username;
1const username = data?.accounts?.?.username;