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

128
Visualizações
Cannot check if the variable exist for object

I'm following the solution from https://stackoverflow.com/a/519157/18736427.

However, the console gives me an error that the object I wanna test is undefined...

I wanna test if the object exists, if not, then console.log('False');, but it gives me an error of 'undefined'

Therefore the code after the check cannot be executed...How do I fix this?

const btn = document.querySelector('.test');

//const data1 = {
  //apple: 'red'
//}

const data2 = {
  banana: 'yellow'
}

btn.addEventListener('click', function() {
  if (typeof data1['apple'] !== 'undefined') {
    console.log('Yes');
  }
  
  console.log('False');
});
<button class="test">Check</button>

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

try:

const btn = document.getElementsByClassName('test');

if (typeof data["apple"] !== 'undefined') {
    console.log('Yes');
  }

you should use data.apple or data["apple"].

about 4 years ago · Santiago Trujillo Relatório

0

Check if you really need to provide red and apple variables.

Instead use a strings for keys

const btn = document.querySelector('.test');
const data = {
 apple: "red"
}

btn.addEventListener('click', function() {
  if (typeof data["apple"] !== 'undefined') {
    console.log('Yes');
  }
  
  console.log('False');
});
about 4 years ago · Santiago Trujillo Relatório

0

If a object variable does not definied, the javascript really do not throw error. But if you write the red variable, the browser try assigns the real value the red variable. So, the method really works: the red varible undefinied.

const btn = document.querySelector('.test');
const data = {
   //do not define apple
}

btn.addEventListener('click', function() {
  if (typeof data['apple'] !== 'undefined') {
    console.log('Yes');
  }
  
  console.log('False');
});
<button class="test">Check</button>

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