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”

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

const jobTitle = person?.['currentJob']?.['title']

To access array positions

const people = [
{
id: 1,
name: 'Foo'
}
];
const person = people[1]?.name;

To invoke functions

const foo = function(callback) {
callback?.('bar');
}

Combined with the “nullish coalescing operator”

const jobTitle = person?.currentJob?.title ?? 'New Job';

Final thoughts

Do you want to read more articles like this?

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