Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

96
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda