DEV Community

Cover image for Optional Chaining Operator
Mansour Mahamat
Mansour Mahamat

Posted on

Optional Chaining Operator

The idea of optional chaining is to make it easy to write code where you need to access properties or values inside an object or array that may or may not be null/undefined. Let’s take a look with this object player :

const player = {
 name: 'Marquinhos',
 team: 'Paris Saint Germain',
 country: 'Brazil',
 birth: {
   months: 'May',
   years: 1994,
 }
}
Enter fullscreen mode Exit fullscreen mode

Let's try to access a value that doesn't exist or is not available.

console.log(player.number)
Enter fullscreen mode Exit fullscreen mode

I'll have an error from the browser.

Let's imagine we call an API and this value should exist but we have a little problem to access this data, this error will break my code.

The Optional Chaining Operator

The JavaScript Optional Chaining Operator is coming with ES2020 that allows us to safely access deeply nested properties of an object without having to check for the existence of each of them.

All you have to do is use the “?.” operator after the property that you want to check for nullish values.

object?.property
object?.[expression]
Enter fullscreen mode Exit fullscreen mode

In our code we can use it like this:

console.log(player?.number)
Enter fullscreen mode Exit fullscreen mode

This operation will check if the parent value exists and if it does not, it returns undefined and we don’t have error. When retrieving data from an API, we may not be 100% sure that a certain object exists in our API response.

Oldest comments (0)