DEV Community

Cover image for What's new in JavaScript: Optional Chaining
AlbertoM
AlbertoM

Posted on • Updated on • Originally published at inspiredwebdev.com

What's new in JavaScript: Optional Chaining

Originally published on inspiredwebdev.com

 

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
}

Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

or using a ternary operator:

const jobTitle = user.work ? user.work.title : ''
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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',
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

And with the Optional Chaining operator:

const elonGraduationYear = elon.education.university?.graduation?.year;
// 1992
const markGraduationYear = mark.education.university?.graduation?.year;
// undefined
Enter fullscreen mode Exit fullscreen mode

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. Follow me on DevTo or on my blog at InspiredWebDev for more.


book banner

Get my e-book on Amazon and Leanpub

Top comments (9)

Collapse
 
thealiilman profile image
Ali Ilman

I've said it before in a related post but I'll say it again! 😂 I'm so delighted to see optional chaining.
I write both in Ruby and JavaScript, and I just love how Ruby's equivalent, the &., makes the code cleaner.

Collapse
 
ajones_codes profile image
Andrew Jones

I think you meant name: ‘Mark Zuckerberg for the second user there ;)

Collapse
 
albertomontalesi profile image
AlbertoM

Yeah, i've copy pasted the objects and forgot to rename it lol

Collapse
 
vedgar profile image
Vedran Čačić

What's the difference from simply writing a.b instead of a?.b? It still returns undefined if a is undefined, as far as I see.

Collapse
 
albertomontalesi profile image
AlbertoM

Actually if you try to access a property of undefined you will get an error Uncaught TypeError: Cannot read property 'b' of undefined

Collapse
 
vedgar profile image
Vedran Čačić

Interesting. I'm quite sure it didn't work that way the last time I tried JS, some 10 years ago. :-D

Collapse
 
nickytonline profile image
Nick Taylor

Also, for TypeScript users, this is currently available in the 3.7 Beta and it should land officially in December.

Elvis

Collapse
 
albertomontalesi profile image
AlbertoM

Yeah, can't wait to be able to use it.

Collapse
 
chattes profile image
Sourav Chatterjee

We just keep bloating the standard with unnecessary add ons just because its cool or in some other Functional Language ...sigh