JScript Language Elements
| Tutorial | Reference |
Controlling Program Flow
| Conditionals | Looping | Break and Continue |
Looping
JScript supports for loops, for...in loops, and while loops. A for loop comprises a for statement, followed by at least one JScript statement. The for statement specifies a counter variable, a test condition, and an action that updates the counter. If the test condition is always met, an infinite loop results, so you should be careful when you design loops.NOTE: The update expression ("icount++" in the following examples) is executed at the end of the loop, after the block of statements that forms the body of the loop is executed, and before the condition is tested.
For historical reasons, the name of the counter variable in a loop usually begins with "i", "j", "k", "l", "m", or "n". Sometimes programmers use just the one letter. This practice, though somewhat dated, does have the advantage of making it easy to recognize loop counter variables.
EXAMPLE
var sum = 0; for(var icount = 1; icount <= 10; icount++) // Counts only up through 10. { sum += icount; document.write(icount + ": "); document.write(sum + "<br>"); } var sum = 0; for(var icount = 1; icount > 0; icount++) // MISTAKE!! This is an infinite loop. { sum += icount; document.write(icount + ": "); document.write(sum + "<br>"); }The for...in Loop
JScript provides a special style of loop for stepping through the all properties of an object (LINK to object info). The following example uses an instance of the pasta object that is defined in the section on objects. The loop counter starts at 0, and steps through to the largest index in the array.
EXAMPLE
for (j in tagliatelleVerde) { // (various JScript commands here) }The while loop
JScript also supports while loops, which are very similar to for loops. The difference is that a while loop does not have an explicit counter variable or update expression. This makes it even more vulnerable to infinite looping, because of the fact that it is not necessarily easy to discover where or when the loop condition is updated. It is only too easy to write a while loop in which the condition, in fact, never does get updated.
EXAMPLE
var junkVar = 365; // The counter is initialized here. while (junkVar >= 1) { if (junkVar > 1) { document.write("Only " + junkVar + "days left! Shop while there's still time!<br>"); } else { document.write("Only ONE DAY left! Better do it now!!<br>"); } junkVar --; // The counter is updated here. } document.write("Gaaah! The year's over! It's TOO LATE!<br>");
© 1996 by Microsoft Corporation.