while( ... ) ... (Iterator)

An iterator mechanism - a loop construct.

Availability:

ECMAScript edition - 2
JavaScript - 1.0
JScript - 1.0
Internet Explorer - 3.02
Netscape - 2.0
Netscape Enterprise Server version - 2.0
Opera - 3.0
JavaScript syntax:-while ( aCondition ) { someCode }
-aLabel: while ( aCondition ) { someCode }
Argument list:aConditionIf true, the loop cycles once more
aLabelAn optional identifier name for the loop
someCodeThe 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.

Warnings:

Example code:

   // 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>");
   }

See also:break, Compound statement, continue, do ... while( ... ), Flow control, for( ... ) ..., for( ... in ... ) ..., if( ... ) ..., Iteration statement, Label, Obfuscation, Off by one errors

Cross-references:

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