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

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

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

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

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 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