2

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
R2rito
  • 21
  • 2

2 Answers2

2

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:

  1. {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.
  2. 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
}
niceman
  • 2,653
  • 29
  • 57
  • Thanks for your answer, I would encourage using Lodash _.get function when need to read a property, (embedded properties) and when you afraid of having undefined for one of them – Mhd Wael Jazmati Aug 25 '22 at 02:22
0

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']) 
Konrad
  • 21,590
  • 4
  • 28
  • 64