DEV Community

Vikas Raj
Vikas Raj

Posted on

ECMASCRIPT: Optional Chaining | Stage 3

Optional chaining is at stage 3 🎉🎉. This one is my favourite. Soon will be available in TypeScript.

Optional Chaining for JavaScript

Status

ECMAScript proposal at stage 4 of the process.

Authors

Overview and motivation

When looking for a property value that's deep in a tree-like structure, one often has to check whether intermediate nodes exist:

var street = user.address && user.address.street;
Enter fullscreen mode Exit fullscreen mode

Also, many API return either an object or null/undefined, and one may want to extract a property from the result only when it is not null:

var fooInput = myForm.querySelector('input[name=foo]')
var fooValue = fooInput ? fooInput.value : undefined
Enter fullscreen mode Exit fullscreen mode

The Optional Chaining Operator allows a developer to handle many of those cases without repeating themselves and/or assigning intermediate results in temporary variables:

var street = user.
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
drewtownchi profile image
Drew Town

Definitely one of the things I miss most from c# when I am using JavaScript. I'm glad to see it is making it into the language.

Collapse
 
anwar_nairi profile image
Anwar

This is definitively one of my most awaited features! Tons of checks will blow away!!

Collapse
 
chiangs profile image
Stephen Chiang

Finally, the Elvis operator is entering the building!

Collapse
 
numtostr profile image
Vikas Raj

I was so jealous of our iOS developers when I first saw them using optional chaining in Swift. And finally we'll be blessed with this feature. 👏👏