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

135
Vistas
Should I include an if statement to prevent a redundant iteration in a loop?

You see, I've return this code to reverse the elements of an Array. This array takes two extreme elements and exchanges them like say [1,2,3,4] => [4,2,3,1] => [4,3,2,1]. However when there are odd number of elements there is a redundant iteration where it exchanges the middle element with the middle element itself. I know computers are a lot faster than say 100 years ago, but just in case would keeping my code as it is offset the efficiency gained by using an "if statement" to prevent that one extra iteration? You see I'm a newbie and wanted to know whether an if statement is more computationaly draining than a single extra iteration. Thank you in advance. let arr = [1,2,3,4,5] function reversearray(array){

for(let a=0; a < array.length-a; a++){
    let total = array[array.length-a-1];
    array[array.length-a-1] =array[a];
    array[a]=total;

   
 }
return array;

}

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

No, running an additional if statement for every array position to cover one case scenario is far more inefficient than allowing one "unnecessary" loop iteration.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Neither - make your loop run the correct number of times:

for(let a=0; a < Math.floor(array.length/2); a++){ …
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