Learn JavaScript
Optional Chaining

The problem of non-existing property

Sometimes while writing the code, we do not know whether the object that we are going to access contains all the necessary properties.

In the example given above, accessing the details property of the user returns undefined. This is because the user object does not contain the details property. But when we try to access the address property, assuming that it is nested inside the details property, it results in an error.

However, in many practical cases, getting undefined is convenient.

In the example given below, we are using the conditional operator ? to return undefined while accessing a property that is not stored in the object.

There is no error in the example given above. But we have to use user.details repeatedly. This becomes a matter of concern for deeply nested properties. Multiple uses of the conditional operator also make the code difficult to understand.

In such cases, we can use optional chaining to make the code easy to understand and avoid code repetition.