[Javascript] What is Optional chaining in upcoming ES11

Suraneti Rodsuwan
3 min readApr 29, 2020

--

Photo by Clint Adair on Unsplash

This article was written from my understanding if you see something is not correct, feel free to comment.

Optional chaining is an operator ?. (question mark and dot) that permits reading the value of a property in object same like operator . (dot).

But the difference is an operator ?. will validate the object’s property that we are going to read is empty or not, if so instead of throwing an error, it will fallback undefined.

For example

const obj = { foo: {}}console.log(obj.foo?.bar?.foobar) // undefined// Instead of throwing an error, we've received undefined.
// because of property bar is undefined.

An operator ?. can also validate that the function we’re going to execute in the object exists or not to prevent an error from execution.

Optional chaining is a part of the features in ES11. The status has currently reached Stage 3 at the July 2019 TC39 meeting.

Some browsers already supported both Desktop and Mobile.

Browser compatibility

Alright, I believe that every developer has encountered a nested object at least once in their life, sometimes some property in object disappeared or properties not matched with the validation code from fetching data or some side effect.

This issue will cause an error like Error: Cannot read property ‘x’ of undefined.

The method that we use nowadays.

As you see, we have to write a long-expression to validate the property that we’re going to read in a nested object.

If we did not write an expression, sometimes reading the property in a nested object will possibly cause an error!

But if we using an operation ?.

We don’t have to write a long-expression with operator && for validating property in each layer anymore! (an expression can be longer if your object located in a complex nested object).

Let see all of the ?. abilities!

  1. Validate that the function we’re going to execute in the object exists or not to prevent an error from execution.

2. Using with array access item.

3. Using with expression.

4. Using with nullish coalescing operator.

Operation chaining is just a part of the features in ES2020 (aka ES11), which also has other features to make developing in Javascript further easier hooray!

--

--