Published on

Optional Chaining in Javascript

  • avatar
    David Rhodes

Looking to learn about or brush up on the optional chaining operator? Here are three things I learned while checking in with MDN and trying out a few test cases on their detail page for Optional Chaining, which shows:

The optional chaining operator ?. permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.

The first most obvious thing about the ?. optional chaining operator is that it replaces the && operator when checking for a series of nested objects. One can make that mental leap easily because it's a pattern we've all used and now has a shorter syntax available. We'll take a look at nested objects several different ways within one parent object, adventurer. Here's how to use the operator with simple nested objects, which you can try out in MDN's Javascript sandbox:

Optional Chaining with Nested Properties

Second, it's not just for strict objects, as an Object can also be a function or an array, nested within another object

. Here we apply optional chaining to a nested method and nested array within the adventurer object.:

Optional Chaining with Nested Methods

Third, it returns undefined when tested values are nullish, which is null or undefined, as you can see in all three test cases below where we try it with a property that doesn't exist.

Optional Chaining with Nested Arrays

That's three things you need to know about the new Javascript Optional Chaining. While not accepted by the IE browser yet (shocking, I know) if you're working in React you're transpiling anyway. Try to keep them in mind when slinging your optional chains and you'll be an expert in no time.

Next up? The Nullish Coalescing Operator.