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

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

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 Denunciar

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