Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

94
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda