Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!