O'Reilly logo

Learning JavaScript by Shelley Powers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required