Core JavaScript

Do-While Loops

Like while loops, do-while loops continue looping as long as a boolean condition is true. Do-while loops differ in that no check is made before entering the loop. So, they always loop at least once. The code below illustrates this in the first loop with a boolean value that is false. The second loop runs over a set of values for i. This second loop would run exactly the same if it were just a while loop.

DoWhile.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
</head>
<body>
    <script type="text/javascript" src="DoWhile.js"></script>
</body>
</html>

DoWhile.js

// Loop only once, since the looping condition is always false.
var bKeepLooping = false;
do {
	document.writeln("First Loop Executed<br />");
} while (bKeepLooping);

// Loop multiple times.
var i = 0;
do {
	document.writeln("Second Loop Executed (i = " + i + ")<br />");
	++i;
} while (i < 4);
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.