How to Create the Basic for Loop in Your HTML5 Game

By Andy Harris

Your HTML5 game will undoubtedly need a for loop at some point. The standard for loop counts the values between 1 and 10. The Count to Ten button triggers the count() function. Here’s the code for count():

 function count(){
  output.innerHTML = ";
  for (i = 1; i <= 10; i++){
  output.innerHTML += i + "<br />";
  } // end for loop
 } // end count

Although the count() function clearly prints ten lines, it only has one line that modifies the output div. The main code repeats many times to create the long output.

  1. You can use the output var immediately.

    Because output is a global variable and it has already been created, you can use it instantly. There’s no need to initialize it in the function.

  2. Clear the output.

    Set output.value to the empty string () to clear the output. This destroys whatever text is currently in the div.

  3. Start a for loop.

    The for loop is a special loop used to repeat something a certain number of times. For loops have three components: initialization, comparison, and update.

  4. Initialize your counting variable.

    A for loop works by changing the value of an integer many times. The first part of a for loop initializes this variable (often called i) to a starting value (usually zero or one).

  5. Specify a condition for staying in the loop.

    The second part of a for statement is a condition. As long as the condition is true, the loop continues. As soon as the condition is evaluated as false, the loop exits.

  6. Change the variable.

    The third part of a for statement somehow changes the counting variable. The most common way to change the variable is to add one to it. The i++ syntax is shorthand for “Add one to i.”

  7. Build a code block for repeated code.

    Use braces and indentation to indicate which code repeats. All code inside the braces repeats.

  8. Inside the loop, write to the output.

    On each iteration of the loop, add the current value of i to the output div‘s innerHTML. Also add a break (<br />) to make the output look better. When you add to an innerHTML property, you’re writing HTML code, so if you want the output to occur on different lines, you need to write the HTML to make this happen.

  9. Close the loop.

    Don’t forget to end the loop, or your program won’t run correctly.