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

183
Vistas
Check if a property exists on an object when the object may not exists either?

I can check if a property exists like so:

let myObject = {};
let exists = myObject.myProperty !== undefined;

But how can I check if the property exists when myObject is not defined either, the following errors:

// let myObject = {}; // do not set this
let exists = myObject.myProperty !== undefined;
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

There are several things at play here.
First, to check if the object exists in the current scope, you should use the typeof operator:

let objectExists = typeof myObject !== 'undefined'

this way, the interpreter won't throw an error.

Second, to check if the object has a specific property, it's still best to use the old in operator

let propertyExists = 'myProperty' in myObject

Both of these expressions return a boolean value, true or false.
So, for safe checking, you might use:

if(typeof myObject !== 'undefined' && myProperty in myObject) {
  // do your stuff
}

if you try to use the newer form of myObject?.myProperty it will still throw a ReferenceError if you haven't declared myObject

and if you use myObject.hasOwnProperty(myProperty) you might get a misleading result, if your object inherits from another and the property belongs to the ancestor

about 4 years ago · Juan Pablo Isaza Denunciar

0

if myObject doesn't exist at all, use try/catch

let exists;
try {
exists = myObject.hasOwnProperty('myProperty');

}catch(err){
console.log(err.message) 
}

if it's null or undefined, Use ?. (optional chaining) operator:

let exists = myObject?.hasOwnProperty('myProperty');
about 4 years ago · Juan Pablo Isaza Denunciar

0

Since the myObject variable might not be defined (as per your question), you must wrap your code with try/catch in order for the flow not to break:

let exists = false;

try{
  // try to access "a" property of myObject
  exists = myObject?.a;
}
catch{
  // because myObject is not defined, the catch block is invoked
  console.log("myObject", "is not defined")
}

console.log({exists})

about 4 years ago · Juan Pablo Isaza 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