DEV Community

anjalyyy1
anjalyyy1

Posted on

Optional chaining in Javascript

Optional chaining is a way to safely access nested properties without getting the nasty Uncaught TypeError: Cannot read property "something" of undefined.

Suppose, we have an object such as

const user = {
    name: "Chris",
    details: {
        age: 30,
        email: "chris@xyz.com",
    }
}
Enter fullscreen mode Exit fullscreen mode
const userAge = user.details.age; // 30
const userStreet = user.details.address.street; // Error !!!
Enter fullscreen mode Exit fullscreen mode

Accessing any property of a non-existent property will result in an error. We can easily resolve this error by having multiple checks like

const userAddress = user.details.address ? user.details.address.street : null;
Enter fullscreen mode Exit fullscreen mode

This just gets uglier if there are more nested properties or if the top-level properties don't exist. I used to use lodash _.get to resolve this. But javascript has now given us optional chaining to overcome this without using any extra dependency. It just goes like this:

const userAddress = user.details.address?.street

The optional chaining ?. stops the evaluation if the value before ?. is undefined or null and returns undefined. This is much cleaner than what we had before. Also bear in mind that ?. just keeps the value optional before it and not after that. The properties after that are accessed regularly.

The optional chaining also works with square brackets and functions like so:

obj?.[prop] -> returns obj[prop] if obj exists, otherwise undefined.
obj.method?.() -> calls obj.method() if obj.method exists, otherwise returns undefined.

Top comments (0)