|
The while Loop
By Stephen Bucaro
A loop structure allows you execute a series of statements over and over.
Several kinds of loop structures are available in Java Script, the while
loop evaluates an expression, and while the expression evaluates to true,
the while loop will repeatedly execute a series of statements. The
syntax for the while loop is shown below.
while(condition)
{
statements;
}
The Condition expression inside the brackets is evaluated. The result
of that evaluation can be true or false. If the result is true
the statements inside the curly brackets will be executed. If the result is
false, the loop terminates and program flow continues with the next
statement following the while loop structure.
var price = 10.00;
while(price > 5.00)
{
price -= 1.00;
}
alert("The final price is: " + price);
In the example above, the variable price is initialized to 10.00. The
Condition expression inside the while loop brackets tests the value of price
to see if it's greater than 5.00. If the value of price is greater than 5.00,
the statements inside the curly brackets are executed; 1.00 is subtracted from
price. The condition expression again tests the value of price.
After the statements inside the curly brackets are executed five times, the
value of price is no longer greater than 5.00. The result of the condition
expression evaluation becomes false, the while loop terminates.
program flow continues with the next statement following the while loop
structure, which creates a message box displaying the final value of
price (5.00).
The do/while Loop
A structure closely related to the while loop is the do/while
loop. The syntax for the do/while loop is shown below.
do
{
statements;
}
while(condition);
|