In this tutorial, you will learn about optional chaining, what it is, and why you should be using it. Most importantly you will learn how to install it so you can start using it within your project. The best way to describe optional chaining is to show a useful problem that it solves, 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. You can not guarantee the shape of the data being returned, what properties are mandatory and which ones are optional. Let us say we have this object structure returned by the API:

AddressLine1 is an optional field that may or may not be returned. In order to write code that parses AddressLine1 you need to check if it exists before you use it, otherwise an exception would be thrown:

Having checks like this in your code is super important, without them your application might blow up in unexpected ways. The trade-off from writing all this defensive boilerplate code is that its tedious work. It also results in harder to understand bloated code. This is where optional chaining comes in handy. Optional chaining provides a simplified syntax that allows you to check if a property has been set using the ? operator, like so:

In this snippet, no exception will 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. It makes me super happy it is now coming to JavaScript!

How To Enable Optional Chaining

To enable optional chaining, you need to install a package. At the time of writing, optional chaining is not natively supported in Javascript, it is a new feature introduced in ES2020. Until it is fully adopted we can get all the optional goodness by installing a package!

After installing the package, you need to ensure it is registered within your babel plugins section, like so:

After optional chaining is enabled, you can simply put a ?. directly after any property and automatic null checking will start working. You can do anything after the ?. and the code will not be executed if the pre statement is null:

To get a value from config:

To access array items safely:

Another thing worth mentioning is about ESLint. 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. A very crude example of how that config file could look is shown below:

That covers it. optional chaining is a great addition to Javascript, happy coding!