Loops

There are two kinds of loops; for loops, ones that do things for each time with a predefined count/set, and while loops, which run while a condition is true.

for loops

In JavaScript, the syntax of a for loop is as follows:

for (var i=0; i<20; i=i+1) {
    // Things to do each time.
}

Inside the round brackets, there are 3 pieces of code, separated by semicolons (;).

In general, you can read it as:

for (<initial condition/setup>; <check/stop condition>; <run after each cycle>) {
    // Code
}

Any or all of these 3 pieces can be omitted, but you must keep the semicolons.

This loop will run forever:

for (var i=0; i<5; ) {
    // i never gets incremented, so every time the loop runs, it will remain 0.
}

Similarly, if you leave out the stop condition, it will always run forever. The break keyword can be used like any other line of code, but instead it immediately stops the loop. The continue keyword is like break, but instead of stopping the loop, it just ends the current cycle (iteration), and goes to the next iteration.

There also exists the ability to use a for loop "for each item in this list", but that isn't needed here. It's known as a "for each" loop.

while loops

In JavaScript, the syntax of a while loop is as follows:

while (<condition>) {
    // Code
}

It runs while the condition is true. It's like omitting both the setup and after-each-iteration pieces from the for loop. This is much simpler, but you have to remember to do setup beforehand, and any variable changes must happen inside the loop.

You are much more likely to make a mistake with a while loop, and end up with an infinite loop - one that runs forever. Just close the window though, and it will stop. Worst case - you reboot your computer. (It's only a problem when you have infinite loops that keep robots driving forever, through walls and then they run away.)

Note: The loop only checks the condition at the start of each iteration (both for and while). For example:

var i=0;
while (i==0) {
    i=27;  // i is no longer zero
    console.log("some message");  // this will still run!
    console.log("this will run the first time before i is checked again");
    // before looping again, it checks i, and sees it's not zero, and exits the loop.
}

<!DOCTYPE html>
<html>
<head>
    <title>My First Loop</title>
</head>
<body>
    <script>
        var i=0; // set initial variable
        for( ;i<=5; )
        {
            // print out text
            document.write("Inside for loop");
            document.write("<br>");
            i=i+1; // increment the variable i by 1
        }
    </script>
</body>
</html>

The first time this loop runs, what is the value of i?

Q1: Write down the value of i at the start of each iteration (including the first) in the loop, in order of execution. (This is Q1 on the assignment.)


<!DOCTYPE html>
<html>
<head>
    <title>My First Loop</title>
</head>
<body>
    <script>
        var i=0;
        for ( ; i<=20; i++) {
            document.write("<br>","Inside the first for loop");
 
            // if i is greater than or equal to 5 and i is less than or equal to 10
            if (>= 5 && i <= 10) {
                break; // end the loop
            } else {
                // the parseInt(i) makes a number from i, but i is already a number
                // so we don't need it
                // a%b means "the remainder of a divided by b"
                // (known as modulus or modulo or just mod for short)
                var j=i%2;
                document.write("Inside the else condition");
            }
 
        }
    </script>
</body>
</html>

Q2: Write down each value of i and j for each iteration of the loop, in the order of execution.

Hint: Watch out for the break statement!


Nested loops

Just like if statements, loops can be nested inside each other. For instance:

for (var i=0; i<10; ++i) {
    for (var j=0; j<10; ++j) {
        var num = i.toString() + j.toString();
    }
}

This is a very convoluted way of counting to 100. For every iteration in the outside loop (with the variable i), the inside loop (with variable j) will complete a full set of (10) iterations.

Obviously, we must use different variable names or the values will overwrite each other. When we create var num, we take i and convert it to a string, then do the same for j, and add the two together.

Because we are adding strings, the characters within are simply combined, or concatenated, so no maths is actually performed. This script will make the strinng "00", then "01", "02", up to "09" for all the values of j (while i remains 0). Then, i becomes 1, and the strings "10", "11", "12" through "19" are generated, and so on for increasing values of i and j up to "99" before exiting.


Code appears to be from https://web.archive.org/web/20180327090707/https://www.mindstick.com/blog/390/using-javascript-nested-loops

<!DOCTYPE html>
<html>
<head>
    <title>Nested loops in JavaScript</title>
</head>
<body>
    <script>
        var i, j, mulTot;  // you can also declare variables beforehand.
        for (= 1; i <= 15; i++) {
            for (= 1; j < 15; j++) {
                mulTot = i * j;
                // As both the if and else are the same, I've removed
                // the condition as it's superfluous.
                mulTot = " " + mulTot;
                document.write("Inside the second/nested loop");
            }
            document.write("<br>");
        }
 
    </script>
 
</body>
</html>

Q3: Write down the values of i and j, together, for each iteration of the inner loop, in order of execution.


Which loop to use

When using a loop, you should take care to pick the right one, although both kinds are often interchangeable (in JavaScript, at least).

A for loop has places available for setup and end-of-iteration code. It's designed to run a set number of times, whether that's a variable with that number, or you enter the specific number yourself (e.g. 15).

A while loop is used when you want to run until something changes, e.g. wait until the light goes green, then drive. You must write setup code outside the loop, and any changes to variables must be done inside the loop. If you forget, you might end up with that infinite loop (don't stay waiting at a green light)!


Q4: Change each of the for loops into while loops for the previous questions.

(Not part of assignment): Which loop is better for each of the questions?