Suppose you wanted to
perform a statement or series of statements 10 times. You could write these
statements 10 times over, but this makes for very long, cumbersome code. Using a
loop simplifies the process.
for loop
The format for the for loop is as follow:
for (initial-counter; test condition; increment counter) { statements; } |
A counter is what keeps track of how many
times the loop has executed. The initial-counter is set one time. The test
condition is used to test the value of the counter each time before entering the
loop. The counter is incremented one each time the loop has completed. Below is
an example. The writeln statement will execute a total of 10 times.
var i; for (i = 1; i < 11; i++) { document.writeln("Inside loop number " + i + "<br>"); } |
Variable i is the counter used and it is
initialized to 1. A test is made to make sure that i is less than 11. The
writeln is executed and then i is incremented by 1. Another test is made for
less than 11, the writeln is executed, i is incremented, and so on.
while
loop
In a while loop, statements are executed
over and over until the condition fails. Below is the format.
while(condition) {statements; } |
Below is an example you can test. In this
example, the counter variable i is initialized to 0. Before the statements in
the loop are executed, the condition must be true. If so, the writeln is
executed and i is incremented. The statements continue to be executed until the
condition fails.
var i = 0; while(i < 10) {document.writeln("Inside loop number " + i + "<br>"); i++; } |