Why to use optional chaining operator (?.) in object in Javascript?

In JavaScript, the question mark (?) can be used in combination with a dot (.) to form an optional chaining operator (?.). This operator allows you to safely access properties and methods of an object without causing an error if the object is nullish (i.e., null or undefined).

For example, consider the following object:
const person = { 
    name: 'Alice', 
    age: 30, 
    address: { 
        street: '123 Main St', 
        city: 'Anytown', 
        state: 'CA' 
    } 
}; 

If you want to access the state property of the address object, you might write:
const state = person.address.state; 
However, if the address property is nullish (i.e., null or undefined), this code will throw an error.

To avoid this error, you can use the optional chaining operator (?.) like this:
const state = person.address?.state;
If address is nullish, the expression person.address?.state evaluates to undefined, without throwing an error.

So, the ? in object notation in JavaScript is used to safely access properties and methods of an object without causing an error if the object is nullish.

Comments

Popular Posts