Availability: |
| ||||||||
JavaScript syntax: | - | aLabel: do { someCode } while (aCondition ); | |||||||
Argument list: | aCondition | This must prove true for a subsequent cycle to start | |||||||
aLabel | An optional identifier that names the loop | ||||||||
someCode | The 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.
In Netscape 4, there is a bug with labelled continue statements and do ... while loops that causes the continue to vector to the top of the loop without testing the condition. This can set up an endless loop. You could work round this by creating a while loop and modifying the test condition.
<HTML> <HEAD> </HEAD> <BODY> <SCRIPT> myCounter = 10; do { document.write(myCounter); document.write("<BR>"); myCounter++; } while(myCounter < 35); </SCRIPT> </BODY> </HTML>
ECMA 262 edition 2 - section - 7.4.3
ECMA 262 edition 3 - section - 7.5.2
ECMA 262 edition 3 - section - 12.6.1
Prev | Home | Next |
DL.compact | Up | Doctype object |
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. |