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

336
Visualizações
What is the best option, a loop inside a conditional or a conditional inside a loop?

Seems obvious, but let's say we have 2 arrays and I want to push some objects inside if certain condition is true. Generally speaking, it would be better like this:

let arr1 = [];
let arr2 = [];
if(someCond){
  for(let i=0;i<5;i++){
    arr1.push(i)
  }
}
else{
  for(let i=0;i<5;i++){
    arr2.push(i)
  }
}

or like this:

let arr1 = [];
let arr2 = [];
for(let i=0;i<5;i++){
  if(cond) arr1.push(i)
  else arr2.push(i)
}

I think the second option looks shorter, but maybe it's worse in performance.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The best is:

const arr1 = [];
const arr2 = [];
const cond = Math.random() > 0.5;
const arr = cond ? arr1 : arr2;

for(let i = 0; i < 5; ++i){
  arr.push(i);
}

console.log('arr1', arr1);
console.log('arr2', arr2);

about 4 years ago · Juan Pablo Isaza Relatório

0

Better to execute the loop one time than the length of array so this is the better of your options

if(someCond){
  for(let i=0;i<5;i++){
    arr1.push(i)
  }
}
else{
  for(let i=0;i<5;i++){
    arr2.push(i)
  }
}

Because you only execute the conditional one time then..

about 4 years ago · Juan Pablo Isaza Relatório

0

As the path of processing this code, i get the following
For every item in the array, i must check the condition
Or no the first option, for this condition, i must do this, otherwise, do that to every item.

The first option, is better in performance, but, unless you're working with BigData i don't think this will influence the processing at all as both are simple instructions to be processed.

This of course depends on the number of itens you're looping and on the complexity of the conditional.

If you use a function in the condition, it'll use more memory, so the first option will be better.

If your condition is simples and your items collection not too large, you are free to use any without problems.

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