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

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

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 Denunciar

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 Denunciar

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