In this tutorial, you will learn about the optional chaining, what it is, why you might want to use it and how to start using it within your project. Lets first start with the most common situation where optional-chaining comes in handy, dealing with JSON returned from an external API. Imagine you need to call an external API that returns a complex response. The external API is outside your sphere of influence. You can not change the code. It is not versioned. You can not guarantee what properties in the response will be set. Lets say we have this object structure returned by the API:

Address line 1 is an optional field which may or may not exist on each API call. To return AddressLine1 you need to check if it exists before you return it, otherwise an exception would be thrown:

Writing all this boilerplate code not only results in harder to understand bloated code, but it also gets tedious fast. Having all these checks are an important part of your codebase otherwise your app might blow-up in unexpected ways. Instead, with optional chaining you can check if a property has been set using the ?. operator, like so:

In this snippet, no exception will ever be thrown regardless if AddressLine1 exists or not. As you can see, the optional chaining version is a cleaner, safer and easier to understand approach. This is why optional chaining is such a useful feature, it allows you to write simplified null checking code. This type of null checking has been a part of C# for years and I have always found it a really handy feature.

Installing Optional Chaining

To enable optional-chaining, install it, like this:

After installing it, you need to ensure it's registered within your babel plugins section, like so:

After optional chaining is enabled, you can simply put a ?. directly after any property and you get automatic null checking. You can do anything after the ?. like in the example below that does an includes check as long as countries exist:

To get a value from config:

To access array items safely:

One word of warning, if you use ESlint on your project you may see a lot of errors and warnings around your optional chains. Make sure you add the babel-eslint to your es-lint config, here is a very crude example of how that config might look: