Skip to content

Combining loop and if Structures

Question

What can we do when we combine loops and ifs?

Answer

Everything! That pretty much sums up programming

  • Repetition (Loops) and Logic (Ifs)
    • Flow control
      • What should I do inside this iteration?
      • What color should I draw this pixel?
      • Should I add or subtract?
      • What code should I run for this record?
      • Is this a valid number or should I ask the user to enter it again?
      • Should a new page be started?
      • Should a total summary page be printed now?
    • Ending the loop
      • Should I stop this loop now?
      • Did they enter the code to end the loop?
      • Did I reach some value where I'm supposed to stop the loop?
      • Is everything OK? Is there an error that should stop the loop?
      • Are there any more records?

Adding Logic to a Loop

We've seen this loop before

1
2
3
4
5
6
7
8
let counter;

counter = 0;

while (counter < 5) {
    document.write("Here's a line of output.<br />");
    counter++;
}

Let's add an if statement and output something different depending on the value of the loop counter.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
    Adding logic to a loop
*/
function addingLogicOne() {
    "use strict";

    // Declare Constants
    const LOOP_LIMIT = 5;
    const INITIAL_VALUE = 0;

    // Declare Variables
    let counter;

    // Assign values to variables
    counter = INITIAL_VALUE;

    // Now with logic
    while (counter < LOOP_LIMIT) {
        if (counter === INITIAL_VALUE) {
            document.write("Here's the first line of output!<br />");
        } else {
            document.write("Here's a line of output.<br />");
        }
        counter++;
    }
}

Let's expand this some more.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
    Adding more logic and more lines of text
*/
function addingLogicTwo() {
    "use strict";

    // Declare Constants
    const SECTION_COUNTER = 1;
    const SECTION_LINE_COUNTER = 1;
    const SECTION_END = 5;
    const LOOP_LIMIT = 20;
    const LOOP_COUNTER = 1;

    // Declare Variables
    let counter;
    let section;
    let sectionCounter;

    // Assign values to variables
    counter = LOOP_COUNTER;
    section = SECTION_COUNTER;
    sectionCounter = SECTION_LINE_COUNTER;

    while (counter <= LOOP_LIMIT) {
        if (sectionCounter === 1) {
            document.write("<span class='blueText'>Section "
                    + section + ":</span><br />");
            section++;
        }

        document.write("    Line number: " + counter
            + ", section line: " + sectionCounter + "<br />");

        if (sectionCounter === SECTION_END) {
            document.write("<br />");
            sectionCounter = 1;
        } else {
            sectionCounter++;
        }

        counter++;
    }
}

Testing Input Data in Loops

We may have to do validation inside loops, which means we need to nest an if statement inside our loop.

** Click me to run isNumericUsage() function call **

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
    Here's how to use the isNumeric() function.
*/
function isNumericUsage() {
    "use strict";

    // Declare Constants
    const INITIAL_VALUE = 0;
    const LOOP_LIMIT = 5;

    // Declare Variables
    let entry;
    let counter;

    // Ask a user to enter five things
    for (counter = INITIAL_VALUE; counter < LOOP_LIMIT; counter++) {
        // Get a number or a string
        entry = prompt("Enter five words or numbers");

        if (isNumeric(entry)) {
            // In here what was entered IS a number.
            document.write("You entered a number: " + entry + ".<br />");
        } else {
            // In here what was entered is a not numeric.
            document.write("You entered a string: " + entry + ".<br />");
        }
    }
}

Here's a larger example

** Click me to run numberCheck() function call **

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
    This is a larger example of checking an
    entered value for a valid number.
*/
function numberCheck() {
    "use strict";

    // Declare Constants
    const INITIAL_VALUE = 0;
    const QUIT_CODE = "quit";

    // Declare Variables
    let enteredNumber;
    let total;
    let loopAgain;

    // Assign initial values to variables
    total = INITIAL_VALUE;
    loopAgain = true;

    // Get numbers from user
    while (loopAgain) {
        enteredNumber = prompt("Enter a number or \"quit\" to end.");
        if (isNumeric(enteredNumber)) {            // <-- test for a number
            enteredNumber = Number(enteredNumber);      //
            total += enteredNumber;                     // <-- It is a number
            document.write("You entered the number "    //     in here.
                    + enteredNumber + "<br />");       //
        } else {
            if (enteredNumber === QUIT_CODE) {
                loopAgain = false;                              //
            } else {                                            // <-- NOT a
                alert("Not a number, please enter a number.");  //     number
            }                                                   //     in here.
        }
    }

    // Output total
    document.write("<br />Total: " + total);
}

And one more even bigger example. You can never have too many examples!

** Click me to run aLittleBiggerExample() function call **

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
    This function prompts the user for a series of
    numbers and stores how many even and odd numbers
    were entered. It also checks the data to make sure
    it is a number. The function displays the results and ends
    when the user enters "quit".
*/
function aLittleBiggerExample() {
    "use strict";

    // Declare Constants
    const INITIAL_VALUE = 0;
    const ODD_NUMBER = 1;
    const EVEN_NUMBER = 0;
    const QUIT_CODE = "quit";

    // Declare variables
    let evens;
    let odds;
    let evenOdd;
    let entry;
    let loopAgain;

    // Assign initial values to variables
    evens = INITIAL_VALUE;
    odds = INITIAL_VALUE;
    loopAgain = true;

    while (loopAgain) {
        entry = prompt("Enter a number, any number, "
                + "or \"quit\" to stop.");

        if (isNumeric(entry)) {
            // It's a number!
            entry = Number(entry);
            evenOdd = entry % 2;
            if (evenOdd === EVEN_NUMBER) {
                evens++;
            } else if (evenOdd === ODD_NUMBER) {
                odds++;
            }
        } else {
            // Not a number in here!
            if (entry === QUIT_CODE) {
                loopAgain = false;
            } else {
                alert(entry + " is not a number, "
                        + "please try again.");
            }
        }
    }

    // Display the results
    document.write("You entered " + evens
            + " even number(s).<br />");
    document.write("You entered " + odds
            + " odd number(s).<br />");
}

Stopping a loop

How do I stop this thing? Shutting down a loop when you want to.

There are several ways to stop a loop. Some of them require that we do some type of test inside the loop. Here's the most basic example with the test being the while() test. This is very common.

** Click me to run firstStop() function call **

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
/*
    The simple test to stop a loop
*/
function firstStop() {
    "use strict";

    // Declare Constants
    const QUIT_CODE = "quit";

    // Declare variables
    let entry;

    while (entry !== QUIT_CODE) {
        entry = prompt("Enter a word, \"quit\" to stop.");
        document.write("You entered: " + entry + "<br />");
    }
}

Sometimes we need to test a condition and then quit before we do some task. We don't want to add something to a total if they entered "quit", for instance. We can do this with an if statement like this:

** Click me to run secondStop() function call **

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
    A simple way to stop a loop and only do a task if
    the user did not enter "quit".
*/
function secondStop() {
    "use strict";

    // Declare Constants
    const INITIAL_VALUE = 0;
    const QUIT_CODE = "quit";

    // Declare variables
    let entry;
    let total;

    total = INITIAL_VALUE;

    while (entry !== QUIT_CODE) {
        entry = prompt("Enter a number or \"quit\" to stop.");
        if (entry !== QUIT_CODE) {
            entry = Number(entry);
            total += entry;
        }
    }
    document.write("Total: " + total);
}

We can also take different paths depending on what was entered.

** Click me to run thirdStop() function call **

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
    Take one of 2 paths depending on what is entered.
    Or quit when "quit" is entered.
*/
function thirdStop() {
    "use strict";

    // Declare Constants
    const INITIAL_VALUE = 0;
    const WORD_LENGTH_LIMIT = 5;
    const QUIT_CODE = "quit";

    // Declare variables
    let shortWords;
    let longWords;
    let entry;
    let wordLength;

    // Assign initial values to variables
    shortWords = INITIAL_VALUE;
    longWords = INITIAL_VALUE;

    // Get numbers from user and count words
    while (entry !== QUIT_CODE) {
        entry = prompt("Enter a word or \"quit\" to stop.");
        if (entry !== QUIT_CODE) {
            wordLength = entry.length;
            if (wordLength <= WORD_LENGTH_LIMIT) {
                shortWords++;
            } else {
                longWords++;
            }
        }
    }

    // Output results
    document.write("You entered " + longWords + " Long words and "
            + shortWords + " Short words.");
}

Stopping Loops with a Boolean

This technique gives the developer more control and is very handy when we start using functions.

This technique requires a boolean variable to work. When we want to stop we just set the variable to false like this:

** Click me to run stopWithBooleanVar() function call **

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
    Stop a loop with a boolean variable
*/
function stopWithBooleanVar() {
    "use strict";

    // Declare Constants
    const LOW_BOUNDARY = 10;

    // Declare variables
    let loopTest;
    let entry;

    // Assign initial values to variables
    loopTest = true;

    // Get numbers from user
    while (loopTest) {
        entry = prompt("Enter a number greater than" + LOW_BOUNDARY);
        entry = Number(entry);
        if (entry > LOW_BOUNDARY) {
            alert("You entered: " + entry);
        } else {
            loopTest = false;
            alert("Good, bye!");
        }
    }
}

This is what we did in the above code.

  • We created a boolean variable and set it to true.
  • We made a while loop with the variable as its test.
  • Then we set the variable to false when we wanted to quit the loop.

Does this look odd to you?

1
2
3
4
// There's no equality test
while (loopTest) {

}

Why didn't we have to do this?

1
2
3
4
// There is an equality test
while (loopTest === true) {

}

If a variable has been set to true or false then it is already a boolean expression. We don't have to test its value, it's already true or false. So, this is correct and is what you will see in books and on the job:

1
2
3
4
// Better way to do this
while (loopTest) {

}

Breaking News!

  • There is one more way of stopping loops that is very useful and is used heavily. It's the break; statement.

  • If JavaScript encounters a break; statement inside of a while or a for loop, it just stops the loop. Just like that!

  • This allows us to stop a loop whenever we want to, not just at the top or bottom of the loop.

  • We can also avoid the sometimes tricky logic of using a boolean variable for stopping. Once the break; is encountered the loop just stops!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
    Stop a loop with the break; statement.
*/
function breakIt() {
    "use strict";

    // Declare Constants
    const INITIAL_VALUE = 0;
    const LOOP_MAXIMUM = 25;

    // Declare variables
    let count;
    let countSquared;

    // Assign initial values to variables
    count = INITIAL_VALUE;

    while (true) {
        document.write(count);

          if (count > LOOP_MAXIMUM) {
              document.write(" is too big!");
              break;
          }

          countSquared = count * count;
          document.write(" squared is " + countSquared + "<br />");
          count++;
    }
}



Setting up test data for Record Sets

We may not always want to loop through the entire record set. This is especially true when we need to test our program. If I have a record set with 1000 records and I need total up a field, I don't want to manually add up 1000 records! However, I can add up the first 5, and just set up my code to loop through the first 5 records to see if my math and code is correct. See below for an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function inventoryItemsRecords() {
    "use strict";

    let currentDescription;
    let currentStockAmount;
    let itemRecords;
    let totalStockAmount;
    let count; // for testing

    // initialize variables
    count = 0;
    totalStockAmount = 0;

    // Open the Inventory Items Records
    itemRecords = openInventoryItemsRecords();

    // Loop through record set
    while (itemRecords.readNextRecord()) {

        // only loop through the first 5 records
        if (count === 5) {
            break;
        }
        count++;

        currentDescription = itemRecords.getItemDescription();
        currentStockAmount = itemRecords.getItemStockAmount();

        // add up stock amount
        totalStockAmount += currentStockAmount;

        document.write(currentDescription + "\t" + currentStockAmount + "<br />");
    }

    document.write("<br/>Total Stock Amount:" + totalStockAmount);
}
The Inventory Item Record Set has 16 total records, but I'm only looping through the first 5. Once I have tested my code and validated that my total is correct, I can remove the loop counter and if statement.



Demos

Demo

  1. Process Student Enrollments
    • unit04/demos/demo-student-enrollments.html
  2. Process Inventory Items
    • unit04/demos/demo-inventory-items.html

Labs

  1. Lab08: Loops and Logic
    • unit04/labs/lab-08-loops-logic.html

Exercises

Exercises

  1. Exercise for Lab08
    • unit04/exercises/exercise-08.html