Working with loops

Looping or iteration control is used to execute some set of instructions repeatedly. Without loops, we would have to write the instructions as many times we want them to execute. Let's print numbers 1 through 5 without using a loop:

<script language="javascript">
document.write (1 + "<br>");
document.write (2 + "<br>");
document.write (3 + "<br>");
document.write (4 + "<br>");
document.write (5 + "<br>");

The following shows the output of the above code:

Before we do this same example with a loop control structure, let's first point out that there are two types of loops:

  1. loops that repeat a set number of times before quitting. This type of loop is created with a for loop. You can use a for loop when you know exactly how many times you want to execute some code.
  2. loops that repeat until a certain condition is satisfied. This type of loop is created with a while loop. The while is useful for those situation in which it is known how many times a specific code needs to be run.

Please access the following pages for more information about JavaScript loop control structures: