Spelchan.com Logo

From Scratch Web Games: A Beginners Guide to Game Development using HTML, CSS, and JavaScript

Chapter 4.14: Looping

Looping is a very common programming task. A loop is essentially a block of code that executes until certain conditions are met. JavaScript supports three types of looping statements. The while statement, the do ... while statement, and the for statement. The first two types of loops are very similar so we will look at them together.

The While statement always has a statement or block of statements tied to it. The condition of the while statement is tested. If the condition is true then the statement or block of code gets executed. When the block of code is finished executing the while statement condition is tested again. If it is still true, the statement or block gets executed again. This continues until the condition is false, at which point the program continues execution on the line after the statement or block of statements. Here is a use of the while statement to see how long an object will fall before hitting the ground.

function calculateFall(acceleration, distance, endLine="\n") {
    let s = "Starting fall at " + distance + endLine;
    let distanceRemaining = distance;
    let velocity = acceleration;
    let time = 0;
    while (distanceRemaining > 0) {
        distanceRemaining -= velocity;
        velocity += acceleration;
        time++;
        s += "Time " + time + ": at " +
                (distanceRemaining > 0 ? distanceRemaining : 0) +
                " (speed " + velocity +")" + endLine;
    }
    return s;
}

You will notice that we first set up our variables for tracking the current velocity and how far the object has to fall before reaching the ground. The while statement simply checks to see if the object has hit the ground. You will notice that the output assumes that the object will not go through the ground. This is done using a trinary operator in the middle of the calculation, which is a very handy feature but if you find this confusing, you could do this calculation outside of the code adding to s.

One thing that starting programmers must watch out for is the infinite loop. This is a loop that will never end, meaning that the program is stuck until stopped by the user. Most web browsers will only let loops run a certain amount of time before bringing up a dialog box telling the user about the problem and letting the user cancel the script. It is surprisingly easy to make this mistake, often by using the wrong condition or adding a semicolon before the branch. While these types of mistakes are initially really hard to find, after you have made these mistakes several times you will start finding it easier to detect these typo problems.

Sometimes the function itself may not always end. An example of this is the 3x+1 conjecture. This is a rather simple mathematical problem that at the time of this writing has no valid proofs (though there are many attempts). The idea is that you have a starting value. If that value is odd, you multiply the value by three then add 1. If the value is odd, you divide it by two. The conjecture is that all positive starting values will eventually reach 1. This has been tested for numbers up to 2^68 so we know our version should stop but it is conceivable that there is a number that would rocket up to infinity, or that would form a loop.

While an interesting mathematical puzzle, it is also a good example of where you would want to use the do...while loop. We want to perform our calculation and then add the result to our list until the value has reached 1 which means we always want to perform the contents of the loop once. Here is my version of the calculation:

function calculate3xPlus1Conjecture(start) {
    let s = ""+start
    let value = start;
    do {
        if ((value % 2) === 0)
            value /= 2;
        else
            value = value * 3 + 1;
        s += ", " + value;
    } while (value > 1);
    return s;
}

One trick that you may want to utilize, is that you will notice I add the first number of the sequence immediately. Then we know that if there is another number in the sequence, we need to add a comma and then the number. This means that we always end up with a proper list. Adding the comma after we add the number would result in an extra comma, which would cost you marks in one of my classes.

The most common type of loop in programming is the for loop. The purpose of this type of loop is to count through a series of numbers. The format of the for statement is:

for (start_condition; end_condition; increment){ /*loop action*/ }

The start condition starts the variable that will be counting to it's initial value. This will generally be 0 or 1, but can be any value. If you are using a variable that has been created outside of the loop then you can skip this part of the statement by simply having the semicolon. I would consider having a /*none*/ comment before the semi-colon so you know that there is no loop initialization.

The second part of the loop which we call the end condition is simply a boolean statement like you would use with an if statement. The loop continues until this condition is no longer true. The condition can be any boolean condition, and could even consist of a function call.

The increment portion is where the counting variable is changed. It is called at the end of every loop iteration. Generally, you will be increasing the counter by 1, but it is valid to decrease the counter, or do any other mathematical operation or call any function you wish. The following sample will add the numbers 1 to 10 together.

var cntr, value = 0;
for (cntr = 1; cntr <= 10; ++cntr) {
    value += cntr;
}

The for statement seems complex. When you get right down to it, the for statement is really a macro statement that makes a while loop behave as a counter. One way of better understanding a for loop is to look at the loop as a while loop. By doing this, you will see what the three parts inside the for loop really do. Here is the above example as a while loop.

var cntr, value = 0;
cntr = 1; // the start condition
while(cntr <= 10) // the end condition {
    value += cntr; // the loop action
    ++cntr; // the increment
}

A more complicated version of the sample would be to calculate the sum of a range of numbers where we start and end at arbitrary integer and increment by an arbitrary integer. Mathematically speaking, we want to program the following equation:

summation of arbitrary range

This is a useful example as it demonstrates all the parts of the loop when using more complicated values. As you will see this is not that difficult.

function calculateRange(start, end, step) {
    let sum = 0;
    for (let i = start; i <= end; i+=step)
        sum += i;

    return sum;
}

More complicated programs will have loops within other loops, which we call nesting. We will explore this next.

Chapter contents

Chapter 4 Contents

4.1 Cheat Sheets

A quick summary of the basics of JavaScript.

4.2 History of JavaScript

A brief look at how JavaScript was written in 10 days.

4.3 Comment Controversy

Comments. Why programmers don't write them, and how they should be written

4.4 Variables

Variables are used to store the state of a program.

4.5 (extra) How Computers Represent Data

Bits, Bytes, and data types.

4.6 Math

Math on the computer similar but some symbol differences.

Math functions

Various math operations can be used through the Math class.

4.8 Strings

Strings are what we call blocks of text and are used extensively.

4.9 Calculating true and false

Determining if a conditional expression is true or false

4.10 if (Conditional statements)

Conditional code using the if statement.

4.11 Nested conditions

If statements can contain other if statements, this is called nesting.

4.12 Switch statement

Switch statements are a way of replacing large number of else if statements.

4.13 Functions

Functions let you put common code into a named function that can be called anywhere.

4.14 Looping

Loops allow you to repeat sections of code until conditions are met.

4.15 Nested loops

Just like conditional statements, loops can be nested but this has some special considerations.

4.16 Accessing the Web page

Scripting languages give us the ability to dynamically change the web page.

4.17 Events

Reacting to the user actions is done by handling events.

4.18 Project: Where’s Wendy

Our project for this chapter is a grid search game.

4.19 Project: Where’s Wendy implementation

My solution to the Project.

← previous section
Functions
next section →
Nested Loops
Table of Contents