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

199
Vistas
What's the best way to use a for-loop in an if/else statement that performs a similar task?

In the code below, even if the if/else statement evaluates to true or false, the doSomething() function is being called. What I was wondering is if there is a way to refactor this code to make it "DRYer." In my actual code, the body of the loop is longer than just a single function being called, so I figure it's worth refactoring.

if (somethingIsTrue) {
    array1.forEach(val => {
        doSomething(val);
    });
} else {
    array2.forEach(val => {
        doSomething(val);
    });
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The conditional operator can be used here. There's probably no need for the anonymous function wrapper either.

(somethingIsTrue ? array1 : array2).forEach(doSomething);
about 4 years ago · Juan Pablo Isaza Denunciar

0

I would isolate the logic into a common function and pass the array to it. The function doesn't need to know which array its iterating over and that logic of deciding which array can be handled outside the function.

let somethingIsTrue = true;
const mArr1 = [1, 2, 3, 4, 5];
const mArr2 = [6, 7, 8, 9, 10];

businessLogic(somethingIsTrue ? mArr1 : mArr2);
somethingIsTrue = !somethingIsTrue;
console.log('---------------------------');
businessLogic(somethingIsTrue ? mArr1 : mArr2);

function businessLogic(mArr) {
  mArr.forEach(val => console.log(val));
}

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