How to use the ?. operator in Javascript

Image source: Kevin Ku/ @kevin-ku-92347 on Pexels

Because in Javascript objects can be very complex and have unpredictable structures, sometimes is hard to access their properties. There’s a real possibility that some nested objects or properties might not exist so when trying to use them, we run into errors. Optional chaining, as a part of ES2020, changes and simplifies the way properties are accessed from deep objects structures. It is also available in TypeScript, starting from version 3.7.

The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

Read more