WEEK: 8

for Loops

For loops Video

In our last section, we were able to make a single question appear. However, what if we want questions to appear a set number of times every time we answer a question?

Here we introduce the for loop. This tool allows us to repeat an action without duplicating code or calling a function multiple times one after another. What is the syntax of a for loop?

    <script>
        for(var i = 0; i < 5; i++)
        {

        }
    </script>

As you can see, there a few parts here.

  1. for - this is the part that tells the computer that it’s a for loop.
  2. ( - this is the beginning of the for loop. The pieces required for the loop to evaluate correctly are inside of the parentheses.
  3. var i = 0; - this is the initialization part of the for loop. var creates a variable i and gives it a value of 0. The statement ends with a ; completing the initialization part.
  4. i < 5 - this section is the evaluation part of the for loop. The evaluation statement checks to see if i is less than 5. If it is, then do everything that is in the {} (curly braces).
  5. i++ - after the body of the for loop (everything in the curly braces) has run, then the variable i is incremented by one, and then the loop continues by evaluating if this new value of i is still less than 5.

The result is that this loop runs five times, from 0 to 4. We can prove to ourselves by creating and running this page.

<html>
    <title>for loops</title>
    <head>
        <script>
            function theForLoop()
            {
                var result = "";
                for(var i = 0; i < 5; i++)
                {
                    result += i + "<br>";
                }
                document.getElementById("theResult").innerHTML = result;
            }  
        </script>
    </head>
    <body onload="theForLoop();">
        <div id="theResult"></div> 
    </body>
 </html>

If you run this page, you see that all numbers print out from 0 to 4 right? So, how do we apply this to our game?

<html>
<title>for Loops</title>

<head>
    <script>
        var actualAnswer;
        var number1;
        var number2;

        function printQuestion() {
            number1 = Math.floor(Math.random() * 10);
            number2 = Math.floor(Math.random() * 10);
            actualAnswer = number1 + number2;
            document.getElementById("theQuestion").innerHTML = "What is " + number1 + "+" + number2 + "?";
        }

        function checkAnswer() {
            var answer = document.getElementById("txtAnswer").value;
            if (answer == actualAnswer) {
                document.getElementById("finalResult").innerHTML = "Good job!";
                printQuestion();

            } else {
                document.getElementById("finalResult").innerHTML = "Try Again!";
            }
        }

        function runGame() {
            for (var i = 1; i < 6; i++) {
                document.getElementById("message").innerHTML += "<h" + i + ">Welcome to our game!!!</h" + i + "></p>";
            }
            printQuestion();
        }
        runGame();
    </script>
</head>

<body onload="runGame();">

    <table>
        <tr>
            <td colspan="2">
                <div id="message"></div>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <hr size="1">
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <div id="theQuestion"></div>
            </td>
        </tr>
        <tr>
            <td>Your answer</td>
            <td><input type="text" id="txtAnswer"></td>
        </tr>
        <tr>
            <td colspan="2"><button id="btnSubmit" onClick="checkAnswer();">Submit</button></td>
        </tr>
    </table>
    <div id="finalResult"></div>
</body>

</html>

If you look carefully, you see that I create a third function called runGame and then call that function in the onload event of the body. Inside the body of the runGame function, I display a message about our game and then call the printQuestion function. Notice that the function call always ends with the () afterward to indicate that it is a function, and then I completed the line with a semi-colon ;.

Run this page. Does it work? Great!

See the Pen JS - for loops by Michael Cassens (@retrog4m3r) on CodePen.


Previous section:
Next section: