Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

93
Views
How to expect possible undefined value with double object bracket notation?

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?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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
}
about 4 years ago · Santiago Trujillo Report

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']) 

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!