Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda