Optional Chaining for reading deeply nested properties
Optional Chaining has made its way up to Stage 2 in the TC39 proposal stages which means the feature is expected to be developed and eventually included in the standard.
This feature is also known as:
- The Existential Operator in CoffeeScript
- Safe navigation or Null conditional operator in a few other languages.
A proposal in Stage 2 still needs to be considered as an experiment, however personally I am hopeful this feature will make it into the language standard.
With that being said, time to learn 📖 about Optional Chaining.
The not so fun way to read the zip code
Say, you are developing code to read the zip code of a lottery winner. The API response can be
null or the user object may not exist in the response.
Optional Chaining ⛓comes to the rescue here
A closer look
The specification is for
?. and not
? which is a significant difference from the CoffeeScript existential operator.
How to use it today?
The proposal is available in the form of a babel plugin.
npm install --save-dev @babel/plugin-proposal-optional-chaining
If you are using TypeScript, this syntax is not supported yet. We may need to wait a bit more to see this adopted in TypeScript.
lodash offers the same feature using the