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

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

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 Denunciar

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 Denunciar

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