USE WHILE LOOPS
Programming languages also include loops. Loops are used to do an action over
and over again. JavaScript uses both while loops and
for loops.
A while loop works such as the following:
while (condition) statement(s) to execute
As long as the condition is true, the statements will be repeatedly executed. The statement block generally includes a counter that modifies the condition; otherwise, you create an infinite loop. If the condition is never true, the statements are never executed.
The following is an example of a while statement:
var counter = 10;
while (counter > 5)
{
document.write
("The counter is now: " + counter + "<br>");
counter = counter - 1;
}
alert("Finished counting!");
Notice the counter variable before the while loop begins. A
value of 10 is assigned to counter. The code block in the loop (the part
between the curly braces) runs five times until the counter value is equal to
5, and the loop stops.
Also note the "<br>" in the document.write
statement. JavaScript allows you to include HTML code to be output by
scripts. In this case, you're inserting a line break after each instance of
the document.write statement output.
The following statement:
counter = counter - 1;
could also be written such as the following:
counter--;
The -- is called the decrement
operator . There is also an increment operator (++) that adds one to the
value. These two statements are equivalent to the following:
counter = counter + 1; counter++;
