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

245
Views
Is it bad practice to have a switch within forEach loop of objects with Javascript?

I needed to change properties from two objects from a array. So I did this

var tabs = [
{name: 'A', visible: false},
{name: 'B', visible: true},
{name: 'C', visible: true}}
];

var changeTabsVisibility = () {
  if(validation()){
    tabs.forEach(tab => {
       switch(tab.name) {
       case 'A':
            tab.visible = true;
            break;
       case 'B':
            tab.visible = false;
            break;
       default:
            break;
       }
    });
  }
}

It worked for what it was supposed to do, but was this a good pratice or the most efficient and comprehensive way to do this?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

I think a clearer, less verbose, and less error-prone version would be to make an object mapping the tab names to their visibility.

const visibilityByTab = {
  A: true,
  B: false
}
tabs.forEach(tab => {
  const newV = visibilityByTab[tab.name];
  if (newV !== undefined) tab.visible = newV;
});

This is much more easily expandable to more tab names, and doesn't carry the possibility of introducing a bug if you ever happen to forget a break.

over 4 years ago · Santiago Trujillo Report

0

I think switch statement is not effeciant in this case.

It's simply converting name to visiblity, isn't it?

Your target is to convert name to visiblity, so it is only need a map which converts the name to visiblity

Here is an example what i thought.

var tabs = [
    {name: 'A', visible: false},
    {name: 'B', visible: true},
    {name: 'C', visible: true}}
];

const NAME_TO_VISIBLE = {
    'A': true,
    'B': false,
    'C': true,
    ...
};

var changeTabsVisibility = () {
    if(validation()){
        tabs.forEach(tab => {
            tab.visible = NAME_TO_VISIBLE[tab.name] || false;
        });
    }
}
over 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!