Update: Optional Chaining is finally in Stage 4!! Which means it is part of the ES2020 specification. It has also already made it to TypeScript v3.7.

Here's the repo with all the info you need.

What is it?

Optional Chaining allows us to check if an object exists before trying to access its properties. Some other languages have something similar. C#, for example, has a Null Conditional Operator that behaves very similarly as the proposed Optional Chaining.

Why do we need it?

Have you ever had to check for the existence of objects or arrays before accessing its properties? If you forget, it may look a little bit like this:



if ( specimen && specimen . arms && specimen . arms . length > 2 ) console . log ( " This is probably an alien " );

The reason why we do these checks is because in JavaScript allows for anonymous objects that don't necessarily have a structure or schema. Therefore if we don't check for parents in an object tree, we get a lot of errors that look like this:

Because, at least in the case of the error, specimen does exist, but it does not have an arms property. Therefore, we tried to get length of something that was undefined .

So, what's the proposal?

Instead of all that, we can chain optional checks like this:



if ( specimen ?. arms ?. length > 2 ) console . log ( " This is probably an alien " );

However, keep in mind that the Optional Chaining operator is ?. not ? - this means that when using it to access an item in an array, it will look like this instead:



var firstArm = specimen ?. arms ?.[ 0 ]; //CORRECT var secondArm = specimen ?. arms ?[ 1 ]; //WRONG

Similarly, when using it to check for the existence of functions:



var kickPromise = specimen ?. kick ?.(); //CORRECT var punchPromise = specimen ?. punch ?(); //WRONG

In this case, we check if kick exists before calling it as a function!

How does it work?

The operator checks if whatever is to the Left-Hand Side of ?. is null or undefined . If it is, then the expression short-circuits and returns undefined . Otherwise, the expression continues to evaluate as if nothing is wrong.

When can I use it?

Well, it is still a proposal so it's not in Vanilla JavaScript just yet. However, it is usable with Babel!

To stay up to date with the status of the proposal, as well as to have a more in-depth understanding and to check some examples, you should check their GitHub repo! You can also find the specs here, but I won't get into that since most of that document goes way over my head 😅

Thank you!

You're welcome! ❤️