Javascript The “optional chaining” operator
Discover how the “optional chaining” operator that comes with the new ES2020 proposal works
One of the features that the ECMAScript 2020 specification brings is a new operator: the optional chaining, present in other languages such as Swift and that comes to Javascript to make it easier for us to work with objects whose keys we are not sure that exist.
In order to summarize the characteristics of this new operator, I have prepared this article that I hope will serve you because it is a very useful feature as soon as we get used to using it.
Let’s go there!
Motivation of the “optional chaining operator”
The reason for being this operator, as I mentioned at the beginning of the article, is to allow us to work with objects of various dimensions without worrying about whether, on the way, we come to a property that is not defined.
For example, suppose we have the following object:
const person = {
name: 'Gerardo',
email: 'mail@mail.com'
}
If we try to do the following:
const jobTitle = person.currentJob.title
the javascript interpreter will throw an error when trying to access a property (currentJob
) whose value is undefined
.
Thanks to the optional chaining operator we can prevent this error as follows:
const jobTitle = person?.currentJob?.title
So if either person
or its currentJob
property is undefined
, the value that the jobTitle
variable will get will be undefined
.
This also applies if the property we are going to access is null
:
const person = {
name: 'Gerardo',
email: 'mail@mail.com',
currentJob: null;
}const jobTitle = person?.currentJob?.title // undefined
Uses of the “optional chaining operator”
To access object properties
This new operator can be used to access the properties of the objects either using “dot notation”, or treating the properties as if they were keys of an array:
const jobTitle = person?.['currentJob']?.['title']
To access array positions
We can also use the operator to access array positions without worrying about whether they are defined or null
:
const people = [
{
id: 1,
name: 'Foo'
}
];
If we want to access the name of the person in second position without worrying about whether it exists or not:
const person = people[1]?.name;
To invoke functions
Además, también podemos emplearlo cuando vayamos a invocar funciones sin necesidad de comprobar previamente que se encuentran definidas:
const foo = function(callback) {
callback?.('bar');
}
Combined with the “nullish coalescing operator”
One of the characteristics that can give us more versatility is to combine this operator with the also recent “nullish coalescing” so that we can write expressions such as the following:
const jobTitle = person?.currentJob?.title ?? 'New Job';
Final thoughts
The appearance of these new operators or, as I have heard in the midudev podcast, “syntactic sugars”, show the degree of maturity that Javascript is gradually reaching. If ECMA Script was a real revolution in the way we worked with Javascript, the subsequent specifications are making it more and more how to work with this language.
Therefore, do not lose sight of the news that is coming out regularly because many of them will become part of our day to day as the famous “spread operator” did at the time.
Do you want to read more articles like this?
If you liked this article I encourage you to subscribe to the newsletter that I send every Sunday with similar publications to this and more recommended content: 👇👇👇