For example, given:
const foo = {name: 'john', age: 12}
console.log(foo?.age);
Given the previous, we are safeguarding by using ? in case foo doesn't have the property age but how can it be done in the next situation (if possible):
const foo = {name: 'john', house: {color: 'white', garage: true }}
console.log(foo['house']?['yard']
How to access a property, inside the property house that might be undefined by using brackets?
First you have a big understanding of the null safe operator, when you say foo?.age you're not safeguarding age field but the foo object itself, examples:
{a: 2}?.age and {a: 2}.age return the same thing, no error will be thrown in both cases, just the value undefined is returned.undefined?.age and undefined.age are different, the first will return undefined while the second will throw an error.Now after you understand what is the null safe operator about, to prevent foo["house"] from throwing because foo might be undefined (not because house property doesn't exist) just use foo?.["house"].
If you want to check for the existence of house property, you can do something like this:
if(foo?.["house"]){
// here house exists so it's safe to read its value using foo.house
}
Or:
if(foo?.hasOwnProperty("house")){
// the same thing, safe to access foo.house
}
Doesn't look great, but it's all we've got
const foo = {name: 'john', house: {color: 'white', garage: true }}
console.log(foo['house']?.['yard'])