Search code examples
javascriptarraysloopsfor-loopcontinue

Continue statement not working properly in JavaScript for loop


I am trying to use continue to omit test3 from being used the total average.

I am not sure what Im doing wrong here. The goal is to use all of the array except for the numbers entered in the test3 text box.

I am trying to gather the sum of all of the array (not including test3) in order to come up with an average at the end of my code.

<html>
    <head>
        <title>Chapter 3 Activity</title>
    </head>

    <body>
        <h1>Test Score Average</h1>
        <p>Insert your 5 test scores in the boxes below</p>

        <form action="">
            Test 1:
            <input type="text" name="test1" id=t1>
            <br> Test 2:
            <input type="text" name="test2" id=t2>
            <br> Test 3:
            <input type="text" name="test3" id=t3>
            <br> Test 4:
            <input type="text" name="test4" id=t4>
            <br> Test 5:
            <input type="text" name="test5" id=t5>
            <br>
            <input type="button" value="Calculate Average" onclick="calculateFunction()">
        </form>

        <script type="text/javascript">
            function calculateFunction() {
                var test1 = document.getElementById("t1").value;
                var test2 = document.getElementById("t2").value;
                var test3 = document.getElementById("t3").value;
                var test4 = document.getElementById("t4").value;
                var test5 = document.getElementById("t5").value;
                var nums = [test1, test2, test3, test4, test5];

                var totalSum = 0;

                for (var i = 0; i < nums.length; i++) {
                    totalSum += parseInt(nums[i]);

                    if (nums[i] === test3) {
                        continue;
                    }
                }
                var average = totalSum / nums.length;

                document.write("Test score average is " + average);
            }
        </script>
    </body>
</html>

Solution

  • The quick fix is to move the if statement above where you add the value to totalSum, like so:

      for (var i = 0; i < nums.length; i++) {
        if (nums[i] === test3){
          continue;
        }
        totalSum += parseInt(nums[i]);
      }
    

    However, this really isn't a good solution. For example, what if all the numbers in your array are equal to 5? Your average would be 0 since we would hit the continue every time. If your goal is to always omit the third element in the array when calculating the average, something like this would be better:

      for (var i = 0; i < nums.length; i++) {
        if (i === 2) {
          continue;
        }
        totalSum += parseInt(nums[i]);
      }
    

    Remember to divide by nums.length - 1 since you're omitting one of the elements when calculating the average.