Optional Chaining in JavaScript
Tags: javascript, webdev, tutorial, beginners
Published: 2022-04-05 08:01:21

Optional Chaining in JavaScript is used to return `undefined` for accessing an object property that doesn't exist and whose parent property is ***nullish (null or undefined).***

If you are unaware that property exists or not and you want to avoid the error that's being thrown, you may want to use optional chaining to get around with it.

In this article, you’ll learn how and when to use Optional Chaining. You’ll also learn when not to use Optional Chaining in JavaScript.

## How it Works

First, let's explore what can go wrong when accessing a property in a nested object.

```jsx
let person = {
    name: "Murtuza",
    work: () => {
        return "Software Developer"
    },
    socials: {
        github: {
            username: "murtuzaalisurti",
            link: "https://github.com/murtuzaalisurti",
            proUser: {
                is: 'no'
            }
        },
        linkedin: {
            username: "murtuzaali-surti",
            link: "https://linkedin.com/in/murtuzaali-surti"
        },
        twitter: {
            username: "murtuza_surti",
            link: "https://twitter.com/murtuza_surti"
        }
    }
}
```

In the above object, let's try to access the property `link` nested within the property `website`. Can we?

```jsx
console.log(person.website.link); //an error will be thrown
```

We get an error,

```jsx
Cannot read property 'link' of undefined
```

The property website doesn't exist in the object!

But, let's add the property `website` to the root object and set the value of it as `null`.

```jsx
website: null
```

Let's check if this works,

```jsx
console.log(person.website.link); //an error will be thrown
```

We get a similar error,

```jsx
Cannot read property 'link' of null
```

As mentioned in the above [definition](#), we can use optional chaining to handle these types of errors! Here's how we can do that.

## **Syntax**

```jsx
// website: property to validate
// link: property to access
website?.link
```

The operator `?.` will check if the property on its left-hand side is `null` or `undefined` and if that's the case, then it will simply return `undefined` without throwing any errors. In other words, this is also known as **short-circuiting**. Otherwise, it will return the value of the property on its right-hand side.

![demo](https://i.imgur.com/rUOx6qB.gif)

Not just that, you can also invoke a function if it exists using optional chaining.

```jsx
person.work?.(args)
```

Also, you can access properties using `[]` brackets.

```jsx
person.socials.github?.["username"]
```

## What You Can’t Do

- You cannot apply optional chaining to the objects that are not declared yet. For example:

```jsx
object?.prop // object is not defined
```

We haven't declared `object`, thus it will throw an error.

- You cannot assign a value to this expression. In other words, the optional chaining expression can't be on the left-hand side.

The below code is not valid.

```jsx
person.socials.github?.["username"] = "name" // not valid
```

## When to Use Optional Chaining?

It's important to note that optional chaining should not be used when it's not necessary to do so. Only use optional chaining when you know that the property that you want to access is optional and not mandatory.

For example, in our object `person`, we can keep the social media platforms optional, so we are not sure if a user has a social media account or not on a particular platform. For that, we can use optional chaining to check if a user has a social media account on a particular platform and if it exists, get the username.

```jsx
person.socials.github?.["username"]
```

But, if we place the optional chaining operator at the root object, then it doesn't make any sense because the root object i.e. `person` must exist and if it doesn't exist, we should get an error!

## Conclusion

In this article, you learned what Optional Chaining in JavaScript is, how it works when to use it, and when not to use it.

To learn more about how Optional Chaining works, make sure to check out the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining#specifications) on it for more details.

> This post was originally published in [Syntackle](https://syntackle.live/blog/optional-chaining-in-javascript-D6SuXGtu0-K5hhtZUqqc/) in collaboration with [blog.shahednasser.com](https://blog.shahednasser.com/optional-chaining-in-javascript/)