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

114
Views
JavaScript if alternative when checking for the same thing multiple times

So I'm trying to check for an undefined object out of multiple ones and then do something with that specific one. This code below works but I can imagine that there's a better way than just using else if 20 times in a row.

   if (duelswins === undefined) {
      document.getElementById('duels_wins').style.display = 'none'
   } else if (duelslosses === undefined) {
      document.getElementById('duels_losses').style.display = 'none'
   } else if (duelskills === undefined) {
      document.getElementById('duels_kills').style.display = 'none'
   } else if (duelsdeaths === undefined) {
     document.getElementById('duels_deaths').style.display = 'none'
   } else if (duelsgoals === undefined) {
     document.getElementById('duels_goals').style.display = 'none'
   } else if (duelskdr === undefined) {
     document.getElementById('duels_kdr').style.display = 'none'
   } else if (duelswlr === undefined) {
     document.getElementById('duels_wlr').style.display = 'none'
   } else if (duelsgwr === undefined) {
     document.getElementById('duels_gwr').style.display = 'none'
   }

There can be multiple ones of those being undefined but it could also be also none of them.

This is just an example, I'm mostly interested if there's and alternative for using so many if statements just for checking basically the same thing over and over again.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Instead of using individual variables you can put these values into an object and then loop over the keys/values. I'm not sure what your requirements are exactly but this might be a step in the right direction:

const data = {
  duels_wins: undefined,
  duels_losses: 123,
  duels_deaths: undefined,
  // ...
};

Object.entries(data).forEach(([key, value]) => {
  if (value === undefined) {
    document.getElementById(key).style.display = 'none';
  }
});
<div id="duels_wins">duels_wins</div>
<div id="duels_losses">duels_losses</div>
<div id="duels_deaths">duels_deaths</div>

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