HomeTutorialsArticlesAbout MeContact

What's new in JavaScript: Optional Chaining

By Alberto Montalesi
Published in Article
October 25, 2019
1 min read
Check out my Github for my free-to-read JavaScript Ebook that covers all the new features from ES6 to 2021. If you want find a great place for interactive tutorials, i recommend Educative where you can find my JavaScript course
This website contains affiliate links.

As of the date of writing this article (24th October 2019), Optional Chaining is at Stage 3 of the TC39 process, meaning that you won’t be able to natively use it in your browser yet.

You can read more about the stages of the TC39 process here.

What is Optional Chaining?

Let’s take these simple Object that represent our Users.

const user1 = {
  name: 'Alberto',
  age: 27,
  work: {
    title: 'software developer',
    location: 'Vietnam',
  },
}

const user2 = {
  name: 'Tom',
  age: 27,
}

Let’s say we want to display the job title of our user. As we can see, work is an optional property of our Object so we would have to write something like this:

let jobTitle
if (user.work) {
  jobTitle = user.work.title
}

or using a ternary operator:

const jobTitle = user.work ? user.work.title : ''

Before we access the property title of work we need to check that the user actually has a work.

When we are dealing with simple objects it’s not such a big deal but when the data we are trying to access is deeply nested, it can be a problem.

This is where the Optional Chaining ?. operator comes to the rescue. This is how we would rewrite our code with this new operator:

const jobTitle = user.work?.title

Done! More concise and readable.

You can read the code above as does the user have a work property? if yes, access the title property inside of it

const user1JobTitle = user1.work?.title
// software developer
const user2JobTtile = user2.work?.title
// undefined

As soon as we hit a property that is not available on the Object, the operator will return undefined

Imagine dealing with a deeply nested object with optional properties such as these two users and their school record.

const elon = {
  name: 'Elon Musk',
  education: {
    primary_school: {
      /*  primary school stuff */
    },
    middle_school: {
      /* middle school stuff */
    },
    high_school: {
      /* high school stuff here */
    },
    university: {
      name: 'University of Pennsylvania',
      graduation: {
        year: 1995,
      },
    },
  },
}

const mark = {
  name: 'Mark Zuckerberg',
  education: {
    primary_school: {
      /*  primary school stuff */
    },
    middle_school: {
      /* middle school stuff */
    },
    high_school: {
      /* high school stuff here */
    },
    university: {
      name: 'Harvard University',
    },
  },
}

Not all of our Users have studied in University so that property is going to be optional and the same goes for the graduation as some have dropped out and didn’t finish the study.

Now imagine wanting to access the graduation year of our two users:

let graduationYear
if (
  user.education.university &&
  user.education.university.graduation &&
  user.education.university.graduation.year
) {
  graduationYear = user.education.university.graduation.year
}

And with the Optional Chaining operator:

const elonGraduationYear = elon.education.university?.graduation?.year
// 1992
const markGraduationYear = mark.education.university?.graduation?.year
// undefined

This is how you access optional properties with this new operator, if you want to start using it, it’s going to be part of TypeScript 3.7 which I highly recommend learning! You can read more about TypeScript 3.7 here;

Alternatively, you can use Babel to start using this operator.


Thank you very much for reading, if you enjoyed this article, please share it with friends and colleagues and if there is a topic you would like me to cover, reach out to me on twitter at @montalesi. Follow me on DevTo or on Twitter for more.

complete guide to modern javascript alberto montalesi ebook bannerGet my ebook on Leanpub or get my course on Educative

Tags

beginnersarticle
Previous Article
Best laptops for programmer under 800 Dollars

Alberto Montalesi

Software Developer

buy me coffee
complete guide to modern javascript book cover

Complete Guide to Modern JavaScript

Get the Course

Category

Article
Tutorial
Challenge

Related Posts

Everything new coming in ES2021
July 25, 2020
3 min
© 2021, All Rights Reserved.

Quick Links

TutorialsArticlesChallenges

Social Media