Optional Chaining Operator

 Optional Chaining Operator


The optional chaining operator (?.) allows you to access nested properties of an object without worrying about potential null or undefined values.


const person = {

  name: 'John',

  address: {

    street: '123 Main St',

    city: 'New York'

  }

};


const street = person.address?.street;

console.log(street);

// Output: 123 Main St


const zipCode = person.address?.zipCode;

console.log(zipCode);

// Output: undefined

In the example above, the optional chaining operator is used to access the street property of the address object. If any intermediate property in the chain is null or undefined, the result will be undefined.

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