Skip to main content

Avoid object property checking with optional chaining

Optional chaining is a relatively new operator that was introduced in ES2020. It allows you to call object properties safely, without throwing an error. When calling properties without this operator, you many crash your applcation with the error Cannot read property '<propertyname>' of undefined.

This can be implemented like this:

const person = { }

const name = person.name
console.log(dude)
// Throws an TypeError: Cannot read property 'name' of undefined

const name = person?.name // undefined
console.log(name)
// Returns undefined

This writing method is always recommended when the property on an object may not be available. Accordingly, a lot of verification code can be saved and the understandability of the code can be increased.