Advanced Statements: The Loops

Before finishing up the remaining two built-in JavaScript objects, we’ll take some time to look at the advanced JS statements: the loops. The looping statements are ones that have a conditional test, just like the conditional if...else... statements covered earlier. However, when the expression evaluates to true, the processor returns to the same condition again at the end of each loop.

The while Loop

The simplest JavaScript loop tests a condition at the start of each loop and continues if the expression evaluates to true. Something in the JavaScript contained in the loop changes at some point, forcing the expression to evaluate to false and the loop to terminate. The keyword while is used to designate this type of loop.

In Example 3-7, one of the test expression variables is incremented with each loop until its value exceeds 10. At that point, the loop terminates.

Example 3-7. Testing a value in a condition in a while loop

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>While Loop</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<script type="text/javascript">
//<![CDATA[

var iValue = 0;
while (iValue < 10) {
   iValue++;
   document.writeln("iValue is " + iValue + "<br />");
}

//]]>
</script>
</body>
</html>

Normally, you do more with a while loop than just increment a value, which you’ll see in more detail throughout the ...

Get Learning JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.