Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

62
Views
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;

}

7 months ago · Juan Pablo Isaza
2 answers
Answer question

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.

7 months ago · Juan Pablo Isaza Report

0

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

for(let a=0; a < Math.floor(array.length/2); a++){ …
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs