JavaScript ?. Optional chaining
Tags: javascript, beginners, programming
Published: 2022-02-02 14:38:29

So, you know the JavaScript [(??) nullish coalescing](https://javascript.plainenglish.io/javascript-operator-5d3bd92e835e) operator.

You are privileged enough to know the ONLY JavaScript operator that takes three operands, the [conditional (ternary) operator](https://javascript.plainenglish.io/javascript-ternary-operator-b76a02c90850).
But what about the optional chaining (?.) operator?

Before you move forward, you should be familiar with the concept of nullish (null or undefined), which is not the same as falsy. A quick look at the nullish coalescing operator will help! Just my 2 cents.

## JavaScript Optional Chaining operator

Following MDN definition, “_The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid_”.

In other words, the optional chaining operator (?.) allows us to check inside an object even if some key-values might not be there.

In other circumstances, this could crash your application.

MDN reports the following example:

```
let nestedProp = obj.first?.second;
```

In brief, we could say that the optional chaining (?.) operator avoids a complete crash of our app by implicitly validating each reference in the chain.

I leave a more [detailed explanation](https://medium.com/p/7a2bce30c450) out of this for the sake of simplicity. 

However, feel free to check it out. It clarifies how we came to have the optional chaining operator.

For the rest of the post, I will use this example object.

```
let books = {
  title: 'Animal Farm',
  novel: {
    title: 'Perfume',
    author: 'P. Süskind',
  },
};
```
If you are not familiar with JavaScript objects or how JavaScript chaining works, you should definitely check the link above.

### The traditional fix

One of the easiest ways to avoid a complete crash is to validate each reference with the logical AND (&&) operator.


```
console.log(books.novel.author); // P. Süskind
console.log(books.horror && books.horror.title); // undefined
```

The second console.log returns undefined because the horror key does not exist. However, the app does not crash.

Following MDN, we understand that "_The logical AND expression is a short-circuit operator. As each operand converts to a boolean, if the result of one conversion is false, the AND operator stops and returns the original value of that falsy operand; it does not evaluate any of the remaining operands_"

This is what happens behind the scenes applying the && operator to validate every key and the book object itself.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/azd8ub63b3vzviwuijap.png)

This is why the app does not crash! It does not even reach books.horror.title.

Although validating each reference works, objects are often more complex than the example above and checking every reference this way is not scalable.

### Enter the optional chaining (?.) operator

As we said, complex objects might have a deeply nested structure.

With the optional chaining operator (?.), however, you don’t have to explicitly test and short-circuit using the logical AND (&&) operator before trying to access the value of a reference.

```
console.log(books.novel.author); // P. Süskind
console.log(books.horror?.title); // undefined
console.log(books.novel.title); // Perfume
```

Using the ?. operator, JavaScript implicitly checks books.horror not to be null or undefined before attempting to access books.horror.title.

Since books.horror is nullish, the expression automatically short-circuits, returning undefined.

Find the [complete version of this article on Medium](https://medium.com/p/7a2bce30c450).

If there is any JavaScript concept you would like me to explain, feel free to drop a comment below!