Javascript The “optional chaining” operator

Discover how the “optional chaining” operator that comes with the new ES2020 proposal works

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.

const person = {
name: 'Gerardo',
email: ''
const jobTitle = person.currentJob.title
const jobTitle = person?.currentJob?.title
const person = {
name: 'Gerardo',
email: '',
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'
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) {

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.

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: 👇👇👇

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store