Optional Chaining

 Optional Chaining


Optional chaining allows you to access properties of an object without causing an error if intermediate properties are nullish or undefined.


const person = {

  name: 'John Doe',

  address: {

    street: '123 Main St',

    city: 'New York'

  }

};


console.log(person.address?.street); // Output: 123 Main St

console.log(person.address?.zipCode?.toString()); // Output: undefined

In the above example, the optional chaining operator ?. is used to access the street property of the address object. If the address object or the street property is undefined or null, it gracefully returns undefined without causing an error.

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...