Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Refactoring JS function and Removing conditional out of loop

As title explains im trying to understand the best way to refactor my function and also remove my if statement from the loop? Any guidance would be appreciated. As I have an idea that me else condition is useless.

function quantitySum(array) {
  let sum = 0;
  for (let i = 0; i < array[0].length; i++) {
    if (array[0].length > 0) {
      sum += parseFloat(array[0][i].f0_);
    } else {
      sum === 0;
    }
  }

  return sum;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You don’t need the if/else condition at all as if there are no items in array[0], there will be no iteration.

    function quantitySum(array) {
      let sum = 0;
      for (let i = 0; i < array[0].length; i++) {
         sum += parseFloat(array[0][i].f0_);
      }
      return sum;
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading