All the fields are defined properly here, but if they're not, we have to handle those errors properly to prevent crashes. Historically we've done this:
const avatar = response && response.accounts && response.accounts.google && response.accounts.google.profile && response.accounts.profile.avatar
// Do something with the avatar
The deeper the properties are nested, the harder it is to write expressions like this. Not to mention, it is a pain to read and easy to get wrong.
## Enter Optional Chaining
Here's how to use optional chaining:
// From our previous example snippet
const avatar = response?.accounts?.google?.profile?.avatar;
See how simple and convenient that was? All we have to do when chaining properties is to use `?.`, instead of `.`. It's so much easier to read this than a string of `AND` conditions.
## Not just for addressing object properties though
Optional chaining can be used in a few other circumstances as well:
### Accessing array items
Let's say we want to make sure the array exists before we read from an index:
const arrayItem = arr?.;
### Calling functions or nested methods
When we're unsure if the function or method exists before calling it:
const user = new User();
### Addressing dynamic property names
When we're using an expression to derive names of properties in objects:
const word = 'onomatopoeia';
const meaning = dictionary?.[word];
### Usage with the null coalescing operator (`??`)
We can combine optional chaining with the null coalescing operator:
// If user.gender is available, assign the value to gender. If not, set it to 'Not Selected'
const gender = user?.gender ?? 'Not Selected';
## What we can't do with it
We can't use optional chaining for assignment:
// This is not valid
const user?.dateOfBirth = '05 Nov 2001';
Are you using optional chaining in your code? Any interesting uses apart from the ones mentioned above? Let me know in the comments.