DEV Community

Cover image for JavaScript ?. Optional chaining
Lorenzo Zarantonello for This is Learning

Posted on • Originally published at Medium

JavaScript ?. Optional chaining

So, you know the JavaScript (??) nullish coalescing operator.

You are privileged enough to know the ONLY JavaScript operator that takes three operands, the conditional (ternary) operator.
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;
Enter fullscreen mode Exit fullscreen mode

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 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',
  },
};
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

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
Enter fullscreen mode Exit fullscreen mode

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.

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

Top comments (0)