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

A variant of the while iterator that checks the condition after execution.

Availability:

ECMAScript edition - 2
JavaScript - 1.2
JScript - 3.0
Internet Explorer - 4.0
Netscape - 4.0
Netscape Enterprise Server - 2.0
Opera - 3.0
JavaScript syntax:-aLabel: do { someCode } while (aCondition );
Argument list:aConditionThis must prove true for a subsequent cycle to start
aLabelAn optional identifier that names the loop
someCodeThe code that gets executed in the loop

A do loop is a variation on the while iterator. A while iterator checks the condition and only executes the code block if it is true. This means that a while loop may never execute even once. A do iterator checks the condition once the code has been executed. This ensures that a do iterator will perform at least one execution of the code block even if the condition proves false the first time it is tested.

ECMA edition 2 compliance merely states that it is a reserved word. At edition 3 of the ECMAScript standard, it is a fully supported requirement of compliance.

JavaScript version 1.2 anticipates this and provides it anyway.

If a labelled continue is used (available from version 1.2 of JavaScript), it is intended that execution should drop to the bottom of the loop and test the condition again before cycling or falling out.

Note carefully the line that increments the counter. If you leave it out, you create an endless loop and the browser locks you out. Maybe it will eventually crash but you may need to wait a long time.

Warnings:

Example code:

   <HTML>
   <HEAD>
   </HEAD>
   <BODY>
   <SCRIPT>
   myCounter = 10;
   do
   {
   document.write(myCounter);
   document.write("<BR>");
   myCounter++;
   }
   while(myCounter < 35);
   </SCRIPT>
   </BODY>
   </HTML>

See also:continue, Flow control, for( ... ) ..., for( ... in ... ) ..., Label, Off by one errors, while( ... ) ...

Cross-references:

ECMA 262 edition 2 - section - 7.4.3

ECMA 262 edition 3 - section - 7.5.2

ECMA 262 edition 3 - section - 12.6.1