Microsoft® JScript™ Controlling Program Flow | JScript Tutorial Previous Next

##### Why Control the Flow of Execution?

> Fairly often, you need a script to do different things under different conditions. For example, you might write a script that checks the time every hour, and changes some parameter appropriately during the course of the day. You might write a script that can accept some sort of input, and act accordingly. Or you might write a script that repeats a specified action.

> There are several kinds of conditions that you can test. All conditional tests in Microsoft JScript are Boolean, so the result of any test is either true or false. You can freely test values that are of Boolean, numeric, or string type.

> JScript provides control structures for a range of possibilities. The simplest control structures are the conditional statements.

##### Using Conditional Statements

> JScript supports if and if...else conditional statements. In if statements a condition is tested, and if the condition meets the test, some JScript code you've written is executed. (In the if...else statement, different code is executed if the condition fails the test.) The simplest form of an if statement can be written entirely on one line, but multiline if and if...else statements are much more common.

> The following examples demonstrate syntaxes you can use with if and if...else statements. The first example shows the simplest kind of Boolean test. If (and only if) the item between the parentheses evaluates to true, the statement or block of statements after the if is executed.

> >     // The smash() function is defined elsewhere in the code.
> >     if (newShip)
> >        smash(champagneBottle,bow);  // Boolean test of whether newShip is true.

> >     // In this example, the test fails unless both conditions are true.
> >     if (rind.color == "deep yellow " && rind.texture == "large and small wrinkles")
> >     {
> >             theResponse = ("Is it a Crenshaw melon? <br> ");
> >     }

> >     // In this example, the test succeeds if either condition is true.
> >     var theReaction = "";
> >     if ((lbsWeight > 15) || (lbsWeight > 45))
> >     {
> >         theReaction = ("Oh, what a cute kitty! <br>");
> >     }
> >     else
> >         theReaction = ("That's one huge cat you've got there! <br>");

##### Conditional Operator

> JScript also supports an implicit conditional form. It uses a question mark after the condition to be tested (rather than the word if before the condition), and specifies two alternatives, one to be used if the condition is met and one if it is not. The alternatives are separated by a colon.

> >     var hours = "";

> >     // Code specifying that hours contains either the contents of
> >     // theHour, or theHour - 12.

> >     hours += (theHour >= 12) ? " PM" : " AM";

> Tip If you have several conditions to be tested together, and you know that one is more likely to pass or fail than any of the others, depending on whether the tests are connected with OR (||) or AND (&&), you can speed execution of your script by putting that condition first in the conditional statement. For example, if three conditions must all be true (using && operators) and the second test fails, the third condition is not tested.

> Similarly, if only one of several conditions must be true (using || operators), testing stops as soon as any one condition passes the test. This is particularly effective if the conditions to be tested involve execution of function calls or other code.

> An example of the side effect of short-circuiting is that runsecond will not be executed in the following example if runfirst() returns 0 or false.

> >     if ((runfirst() == 0) || (runsecond() == 0))
> >     // some code

##### Using Repetition, or Loops

> There are several ways to execute a statement or block of statements repeatedly. In general, repetitive execution is called looping. It is typically controlled by a test of some variable, the value of which is changed each time the loop is executed. Microsoft JScript supports many types of loops: for loops, for...in loops, while loops, do...while loops, and switch loops.

##### Using for Loops

> The for statement specifies a counter variable, a test condition, and an action that updates the counter. Just before each time the loop is executed (this is called one pass or one iteration of the loop), the condition is tested. After the loop is executed, the counter variable is updated before the next iteration begins.

> If the condition for looping is never met, the loop is never executed at all. If the test condition is always met, an infinite loop results. While the former may be desirable in certain cases, the latter rarely is, so take care when writing your loop conditions.

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

> >     var howFar = 11;  // Sets a limit of 11 on the loop.

> >     var sum = new Array(howFar);  // Creates an array called sum with 11 members, 0 through 10.
> >     var theSum = 0;
> >     sum[0] = 0;

> >     for(var icount = 1; icount < howFar; icount++)  {        // Counts from 1 through 10 in this case.
> >     theSum += icount;
> >     sum[icount] = theSum;
> >     }

> >     var newSum = 0;
> >     for(var icount = 1; icount > howFar; icount++)  {        // This isn't executed at all.
> >     newSum += icount;
> >     }

> >     var sum = 0;
> >     for(var icount = 1; icount > 0; icount++)  {        // This is an infinite loop.
> >     sum += icount;
> >     }

##### Using for...in Loops

> JScript provides a special kind of loop for stepping through all the properties of an object. The loop counter in a for...in loop steps through all indexes in the array. It is a string, not a number.

> >     for (j in tagliatelleVerde)  // tagliatelleVerde is an object with several properties
> >     {
> >     // Various JScript code statements.
> >     }

##### Using while Loops

> The while loop is very similar to a for loop. The difference is that a while loop does not have a built-in counter variable or update expression. If you already have some changing condition that is reflected in the value assigned to a variable, and you want to use it to control repetitive execution of a statement or block of statements, use a while loop.

> >     var theMoments = "";
> >     var theCount = 42;        // Initialize the counter variable.
> >     while (theCount >= 1)  {
> >         if (theCount > 1)  {
> >             theMoments = "Only " + theCount + " moments left!";
> >     }
> >         else  {
> >             theMoments = "Only one moment left!";
> >         }
> >     theCount--;        // Update the counter variable.
> >     }
> >     theMoments = "BLASTOFF!";

> Note Because while loops do not have explicit built-in counter variables, they are even more vulnerable to infinite looping than the other types. Moreover, partly because 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. You should be extremely careful when you design while loops.

##### Using break and continue Statements

> Microsoft JScript provides a statement to stop the execution of a loop. The break statement can be used to stop execution if some (presumably special) condition is met. The continue statement can be used to jump immediately to the next iteration, skipping the rest of the code block but updating the counter variable as usual if the loop is a for or for...in loop.

> >     var theComment = "";
> >     var theRemainder = 0;
> >     var theEscape = 3;
> >     var checkMe = 27;
> >     for (kcount = 1; kcount <= 10; kcount++)
> >     {
> >         theRemainder = checkMe % kcount;
> >         if (theRemainder == theEscape)
> >           {
> >                 break;  // Exits from the loop at the first encounter with a remainder that equals the escape.
> >     }
> >     theComment = checkMe + " divided by " + kcount + " leaves a remainder of  " + theRemainder;
> >     }

> >     for (kcount = 1; kcount <= 10; kcount++)
> >     {
> >        theRemainder = checkMe % kcount;
> >        if (theRemainder != theEscape)

> >        {
> >           continue;  // Selects only those remainders that equal the escape, ignoring all others.
> >     }
> >     // JScript code that uses the selected remainders.
> >     }

> >     var theMoments = "";
> >     var theCount = 42;  // The counter is initialized.
> >     while (theCount >= 1)  {
> >     // if (theCount < 10)  {  // Warning!
> >     // This use of continue creates an infinite loop!
> >     // continue;
> >     // }
> >         if (theCount > 1)  {
> >             theMoments = "Only " + theCount + " moments left!";
> >     }
> >         else  {
> >             theMoments = "Only one moment left!";
> >         }
> >     theCount--;  // The counter is updated.
> >     }
> >     theCount = "BLASTOFF!";

© 1998 Microsoft Corporation. All rights reserved. Terms of Use.