Optional chaining operator

 Optional chaining operator


The optional chaining operator (?.) is a new operator in JavaScript that allows you to access properties and methods of an object without worrying if the object is null or undefined. Here's an example:


const user = {

  name: 'John Doe',

  address: {

    street: '123 Main St.',

    city: 'Anytown',

    state: 'CA'

  }

};


const city = user?.address?.city;

console.log(city); // Output: 'Anytown'


const zipCode = user?.address?.zipCode;

console.log(zipCode); // Output: undefined

In the code above, we're using the optional chaining operator (?.) to access the city property of the user.address object. If any of the objects in the chain are null or undefined, the operator returns undefined instead of throwing a TypeError. We can also use the operator to call methods on an object, like this:



const user = {

  name: 'John Doe',

  getAddress() {

    return this.address;

  }

};


const city = user.getAddress()?.city;

console.log(city); // Output: undefined (because user.address is undefined)

In the code above, we're using the optional chaining operator to call the getAddress method on the user object, and then access the city property of the result. Since user.address is undefined, the operator returns undefined instead of throwing a TypeError.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...