Advanced Statements: The Loops






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 Figure, one of the test expression variables is incremented with each loop until its value exceeds 10. At that point, the loop terminates.

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 rest of the book.

The do...while Loop

In the previous section, the while loop showed how a conditional expression is tested before the loop is executed. If the condition fails immediately, the contained code is never processed. There are times, though, when you might want the code to be processed at least once, regardless of the condition and its success or failure. Enter the do...while loop.

Unlike the while loop, the do...while loop doesn't evaluate the conditional expression until after the end of the code block. As such, the block is always processed at least once. The loop in Figure can be modified as follows if the code in the contained block is to be processed at least once:

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

With both the while loop and the do...while loop, the conditional operation determines whether the loop is processed. Any condition can workincluding complicated ones, such as the following:

while (iValue < 10 && iValue >= 3) ...

There is another loopthe for loopwhere you set the number of times the loop contents are processed.

The for Loops

Rather than use a condition, use a for loop to traverse the code contained within a loop a set number of times. There are two different types of for loops, though not all are implemented in all browsers.

The most common for loop, and one implemented in all browsers, has three stages: a variable is set to a starting value; it is updated with each loop; and when the value satisfies a specific condition, the loop is finished:

For (initial value; condition; update) {
...
}

The following code traverses a loop 10 times, printing out "hello" each time:

for (var i = 0; i < 10; i++) {
   document.writeln("hello<br />");
}

A variable, i, is set to zero. With each iteration of the loop, the value is tested to see if the condition is met (value still under 10); if not, the loop code block is processed, and the conditional variable is incremented. The condition can be set by a user variable or by traversing the elements of an array. (Arrays are explored in Chapter 4.)

The second version of the for loop is a for...in loop, which accesses each element of the array as a separate item. The syntax for this handy statement is:

for (variable in object) {
...
}

Before demonstrating the for...in loop, I want to digress for a moment and talk about objects as associative arrays. We'll get into arrays in Chapter 5 and objects starting in Chapter 9, but the for...in is especially useful for a construct known as an associative array.

An associative array is a hash, where each element can be accessed by a key valuea string associated with the value. Objects, such as the document object in JavaScript, are instances of associative arrays. The document object used in previous examples has one item, the writeln function, which is one member of its array of properties. There are actually many such document object properties. Rather than access these by some numeric index, as with most arrays, you use the property name.

Returning to the for...in loop, this control statement can be used to not only traverse an object's properties, but also each property's value. In Figure, this approach is used to print out not only the properties of the object, but their valueusing eval to evaluate the string as if it were a direct statement. The JavaScript for...in statement is used with the window object to find out what properties are available. Many of these will seem very unfamiliar because they're part of DOM Level 2, covered in Chapter 11.

Using for in to expose an object's properties

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Expose the Objects</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Expose Me</h1>
<p>Going undercover to expose the document object's dirty little secrets..</p>

<script type="text/javascript">
//<![CDATA[

for (docprop in document) {
   document.writeln(docprop + "=");
   eval ("document.writeln(document.." + docprop + ")");
   document.writeln("<br />");
}

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

Try this out with various browsers and various objects, and you'll get some interesting results. Though the object implementation is very similar across browsers, it isn't identical. Modifying the code to use different objects (JavaScript, Browser Object or Document Object models), you might also find, as I did, a bugin this case, a bug in Firefox: an unhandled exception based on a nonimplemented property, domConfig.

A third for loop is foreach, implemented in JavaScript 1.6 in Gecko-based browsers. This loop makes use of a callback function in the first parameter, and an object to act as primary reference within that callback function. Since foreach is not standard across browsers, and makes use of functionality we haven't discussed yet, I won't cover it other than to point you to the Mozilla organization documentation on the statement, http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:forEach.


The use of in also works with conditional tests. For instance, to check whether a key (property) exists in an associative array (object), you can use:

if ("URL" in document) {
   alert(document.URL);
}

This syntax is not used frequently, and we'll get more into associative arrays in the next chapter and later in the book. However, if you see code of this nature in the future, you'll recognize it for what it is.

Now that we have much of the functionality of JavaScript behind us, it's time to take a closer look at the built-in JavaScript objects, covered in Chapter 4.



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows