JavaScript loops are similar to those of other high-level languages. They allow statements to repeatedly executed as long as a conditional expression remains true.
The loop statements that JavaScript offers are while, do ... while and for.
The while Loop
This loop structure repeats one or more statements as long as a condition remains true. The condition is checked first so if the condition is initially false the statements will never be executed.
Obviously the loop must contain a statement that allows the condition to become true at some point or the loop will never end.
Example of a while Loop
<script language="javascript" type="text/javascript">
var counter = 1;
while (counter < 20)
{
document.write(counter + " ");
counter ++;
}
</script>
The do ... while Loop
The only difference between this and the while loop is that the condition is checked at the end of the loop therefore the statements enclosed will always be executed at least once.
Again the loop must contain a statement that allows the condition to become true at some point or the loop will never end.
Example of a do ... while Loop
<script language="javascript" type="text/javascript">
var counter = 1;
do
{
document.write(counter + " ");
counter ++;
} while (counter < 20)
</script>
The for Loop
The for loop is designed to iterate a set number of times. It has three parts separated by semicolons.
The initial statement(s). This sets up the initial counter(s) and is executed only once, before the loop body is executed.
The loop condition. This is a conditional expression that is evaluated, normally to see if the loop limit(s) has been reached, before the start of each loop - if it returns false the loop body is not executed.
The end loop statement(s). This updates the counter(s) and is executed after the loop body is executed.
Normally there is one loop counter and a simple conditional expression however, conditions can be as complex as required and several initial and end-loop statements can be separated by commas.
The break Statement
The break statement is used to break out of a loop early i.e. before the loop condition becomes false.
It can be used with all types of loop and is used in conjunction with a conditional expression.
Example of a break Statement
<script language="javascript" type="text/javascript">
// This will print out 1 2 3 4 5 6 7 8
var limit = 8;
for (counter = 1; counter < 10; counter ++)
{
if (counter > limit)
break;
document.write(counter + " ");
}
</script>
The continue Statement
The continue statement allows you to go to the start of the loop without executing all the statements in the loop body.
It can also be used within a while loop and is used in conjunction with a conditional expression.
Example of a continue Statement
<script language="javascript" type="text/javascript">
// This will print out 8 9
var limit = 8;
for (counter = 1; counter < 10; counter ++)
{
if (counter < limit)
continue;
document.write(counter + " ");
}
</script>