The while Loop


The while Loop

Another powerful loop in JavaScript is the while loop. When you want a loop that uses a loop index, you naturally think of a for loop. However, you also might want a loop that doesn't use a loop index at allyou might want to loop only until a certain condition becomes false (such as when you haven't yet found the data item for which you're searching an array). That's where the while loop comes in. This loop evaluates an expression, and if it is true, executes a set of statementsno loop index needed. The loop keeps repeating as long as the specified condition is true.

 while (  condition  ) {  statements  } 

The following parts comprise this loop:

  • condition . A condition that is evaluated before each time through the loop. If this condition evaluates to true, the statements in the loop's body are performed. When condition becomes false, the loop terminates.

  • statements . The body of the loop. These are statements that are executed as long as condition evaluates to true. Although not required, it is good practice to indent these statements.

Like the for and for in loops , the while loop has been around a long time, as you see in Table 3.3.

Table 3.3. The while Loop

Statement

NS2

NS3

NS4

NS6

IE3a

IE3b

IE4

IE5

IE5.5

IE6

while

x

x

x

x

x

x

x

x

x

x

Here's an example. In this case, I'll search an array for a person named Claire using a while loop; when I find Claire, I'll end the loop. Here's what the code looks like:

(Listing 03-04.html on the web site)
 <HTML>     <HEAD>         <TITLE>             Using the while Loop         </TITLE>     </HEAD>     <BODY>         <H1>Using the while Loop</H1>         <SCRIPT LANGUAGE="JavaScript">             <!--  var index = 0, data = new Array(5)   data[0] = "Fank"   data[1] = "Tom"   data[2] = "Claire"   data[3] = "Sara"   data[4] = "Jane"   while(data[index] != "Claire"){   index++   }   alert("Found Claire at index " + index)  // -->         </SCRIPT>     </BODY>  </HTML> 

You can see the results in Figure 3.5, where we've found Claire.That's all it takes.

Figure 3.5. Using a while loop.

graphics/03fig05.gif

Here's one thing to note about the while loop: The condition is tested before the loop's body is executed even once. That's a problem where the code in the loop's body must be evaluated before the condition can be checked (as, for example, when you must perform some complex calculation to determine whether a result is over the maximum possible value). In cases like these, you can use the new do while loop, which is just like a while loop, but where the loop's condition is checked at the end of each loop iteration, not before each iteration.



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net