| Availability: |
| ||||||||
| JavaScript syntax: | - | while ( aCondition ) { someCode } | |||||||
| - | aLabel: while ( aCondition ) { someCode } | ||||||||
| Argument list: | aCondition | If true, the loop cycles once more | |||||||
| aLabel | An optional identifier name for the loop | ||||||||
| someCode | The code that gets looped | ||||||||
Although the while() statement is an iterator, it is functionally related to the if() statement since it will execute the statement block only as long as the condition evaluates to true.
The difference between if() and while() is that if() only processes the statement block once whereas while() processes the statement block repeatedly until something causes the condition enclosed in parentheses to evaluate to false.
A while loop tests the condition before execution of each pass through the loop. If a do loop is supported by the implementations, it would test the condition after each pass through the loop.
A break statement can be used to terminate a while() iterator prematurely, perhaps within a conditional test that is supplementary to the one in the while() heading.
A continue statement can be used to initiate the next cycle of the while() iterator.
The unlabeled form is more commonly used and was available from earlier releases of the JavaScript and JScript interpreters. Labeling was added later at version 1.2 but is not often used.
If a labeled continue is used, the condition is tested again, and the loop will cycle if necessary.
Make sure that something in the statement block will cause the test condition to change to false otherwise you will create an endless loop that can never exit. How this is dealt with depends on what you are doing in the loop and whether the implementation can detect an endless loop situation. It is likely the process containing the JavaScript interpreter will either stall and hang or a runtime error may result. In extreme cases, the hosting application may crash and on some platforms, the entire system may halt. At the very least, you could expect memory and CPU usage to go up while the loop runs. On a multi-user system, you may be able to use an administrator account to kill the offending process.
// An enumerator built with a while statement
var a = 10;
while(a > 0)
{
document.write("*");
a--;
}
// A labelled enumerator
a = 0;
head: while(a < 20)
{
document.write(a);
a++;
if(a > 10)
{
continue head;
}
document.write("*<BR>");
}ECMA 262 edition 2 - section - 12.6.1
ECMA 262 edition 2 - section - 12.7
ECMA 262 edition 2 - section - 12.8
ECMA 262 edition 3 - section - 12.6.2
Wrox Instant JavaScript - page - 23
Wrox Instant JavaScript - page - 25
| Prev | Home | Next |
| Wheel() | Up | Whitespace |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. | ||