In this article, we'll take a look at a proposal that will include optional chaining in JavaScript.

What Is Optional Chaining?

Optional chaining is a technique that can be found in other languages already, such as C# (although their name for this is null-conditional operator . It's a safety mechanism that allows us to check for the existence of an object before accessing its properties.

This is how it's currently implemented in C#:

public class Person { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public Person Spouse { get; set; } } var spouseName = p?.Spouse?.FirstName; // null-conditional operator var spouseName = (p == null) ? null : (p.Spouse == null) ? null : p.Spouse.FirstName; // without the null-conditional operator

Optional Chaining in JavaScript

Quite recently it was announced that the TC39 committee moved the proposal for optional chaining to Stage 3:

WE JUST MOVED OPTIONAL CHAINING IN JS TO STAGE 3 🎉🎉🎉🎉🎉🎉🎉 — Daniel Rosenwasser (@drosenwasser) July 25, 2019

What does this mean for JavaScript developers?

Currently, to check a property that's nested in another object, we need to make a check for the existence of a previous node:

/* Given the following structure: { "user": { "name": "John", "photo": "john.png", "location": { "city": "London", "country": "UK" } } } */ const city = user.location && user.location.city;

Failing to do such checks, we may run into some Uncaught TypeErrors, for example, if we wanted to do an operation on a property that doesn't exist:

const city = user.location.city.toUpperCase(); // throws Uncaught TypeError if location.city doesn't exist

Using the Optional Chaining Operator (denoted by a ? ) we will be able to handle the above using the following formula:

const city = user.location?.city;

The Optional Chaining Operator in JavaScript allows developers to safely check for the existence of deep nested properties in objects.

It's also important to point out that the correct syntax for the Optional Chaining Operator is ?. which means that we need to take some caution when using it:

const firstElement = someObject?.someArray?.[0] // will work const secondElement = someObject?.someArray?[1] // nope - incorrect syntax, not using ?.

From a technical perspective, the way this operator works is straightforward. It first checks whether the value on the left-hand side of the expression is null or undefined . If it is, then it merely returns undefined , otherwise it continues to evaluate the expression and return the correct value.

Note that in Angular we can use a similar feature.

Conclusion

The Optional Chaining Operator is undoubtedly going to great help for JavaScript developers because it will allow us to remove some unnecessary checks for objects. Let's hope it'll be added to the language soon enough!