DEV Community

Cover image for JavaScript Optional Chaining
Alexandru Ghiura
Alexandru Ghiura

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

JavaScript Optional Chaining

I love 💓 “syntactic sugar” and I have been waiting to use this for a long time. Finally, optional chaining is Stage 4 (read more about JS stages) and more importantly it is available in TypeScript from (3.7).

What is optional Chaining

Optional chaining is a process for querying and calling properties, methods on an optional that might currently be null or undefined.

Let me give you an example.

// Let's say we have this object
const person = { name: undefined }

// This will give you an error
// TypeError: Cannot read property 'fname' of undefined
const fname = person.name.fname
Enter fullscreen mode Exit fullscreen mode

To be safe that person exists and person.name exists we would use logical expressions like this:

const person = { name: undefined }
const fname = person && person.name && person.name.fname
Enter fullscreen mode Exit fullscreen mode

But as you can see you need to write a lot of code and if the property you need to access is even deeper in the object your logical expression will be even longer.

The optional chaining operator aims to solve this problem. All you need to write is 👇👇👇

const fname = person?.name?.fname
console.log(fname) // undefined
Enter fullscreen mode Exit fullscreen mode

This will check person and person.name and if one of them is undefined will return undefined.

If you want to learn more about it the proposal page is a great place to start.

How to use the Operator

The operator does not work with Node.js out of the box just yet but you can use it with Babel (setup Babel), add this plugin @babel/plugin-proposal-optional-chaining to .babelrc plugins and you are good to go.

Thank you so much for reading!

If there is anything I can do to help, please reach out. Check out my blog for more articles.

Have a nice day!

Top comments (0)