Home > Back-end >  Should I include an if statement to prevent a redundant iteration in a loop?
Should I include an if statement to prevent a redundant iteration in a loop?

Time:10-09

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;

}

CodePudding user response:

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.

CodePudding user response:

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

for(let a=0; a < Math.floor(array.length/2); a  ){ …
  • Related