The optional chaining ?. is a safe way to access nested object properties, even if a mid property doesn’t exist.
As an example, let’s say we have person objects and most of person have addresses in person.address property, with the street person.address.street, but some did not provide them.
In such case, when we attempt to get person.address.street without having street ,we get an error:
let person = {
}
console.log(person.address.street)
//error
As there is no address in person, an attempt to get person.address.street fails with an error.
But we if use optional chaining , we will get undefined instead of error.
console.log(person?.address?.street) // undefined
In many practical cases we’d prefer to get undefined instead of an error here (meaning “no street”).
One case would be like this ,
let street = person?.address?.street ?? ' No street' ;
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন