[Previous] [Table of Contents] [Next]

Control Structures

Rarely will your scripts be linear. They will generally contain branches, along with control structures that determine which branch should be executed.

if Statement

You can use the if statement in different ways. The following code tests a condition:

if (condition)
{ 
    statements, if condition is true 
}

The condition must be set in parentheses and can contain the comparison operators mentioned earlier. If the condition is true, the statements in the if block are executed. If the block contains only one statement, this statement can follow on the next line, without the braces. Blocks containing several statements must be enclosed in braces, as shown in the following code snippet:

if (value <= 16.0)
{ 
    WScript.Echo("Sorry, you lose the game");
    value = 0
}

The variable value is set to 0 if the current value is less than or equal to 16. The braces enclose a block of statements. By the way, the semicolon in the last statement in a block is optional because the closing brace marks the statement's end.

If you need a condition that executes one of two branches, you use the if…else structure:

if (condition)
{ 
    statements, if condition is true 
}
else
{ 
    statements, if condition is false
}

The if statement tests the condition. If the result is true, the statements in the block following the if statement are executed. If the condition is false, the statements in the else block are executed, as shown here:

if (value <= 16.0)
{ 
    WScript.Echo("Sorry, you lose the game");
    value = 0  
}
else
{ 
    WScript.Echo("Congratulations, you won");
}

TIP
You can omit the braces if a single statement follows if or else.

Conditional Operator

JScript supports a conditional operator that assigns a value based on a condition. The operator uses the following syntax:

(condition) ? value1 : value2

The condition, which is set in parentheses, is followed by a question mark. If the condition is true, the value in front of the colon (value1) is used. Otherwise, the second value is used.

In the following line, if age is equal to or greater than 18, status is set to "Adult". Otherwise, status is set to "Child".

status = (age >=18) ? "Adult" : "Child";

for Loop

You can use a for loop to repeat a block of statements in a defined manner. A counter defines the number of repetitions. The for loop uses the following syntax:

for (initialization; condition; increment statement)
{
    statements
}

Here's an example of a for loop:

for (var count = 1; count <= 100; count++)
{
    statement1;
    statement2;
    
    statementn;
}

The variable count in the header of a loop is set to the start value when the program enters the loop. The optional keyword var declares a local variable for the counter used in the body of the loop. During each pass, the value of count is incremented (using count++) or decremented (using count--) in the third argument. Because ++ follows the variable name, the variable value is incremented at the end of each iteration of the loop. The end condition for the loop is defined in the second argument (count <= 100).

Listing 5-2 uses a loop in a WSH script. (Don't be surprised if this code looks familiar: you saw the VBScript version as Listing 2-1.)

Listing 5-2 WSHDemo.js

//**************************************************
// File:    WSHDemo.js (WSH sample in JScript) 
// Author:  (c) G. Born
//
// Showing interim results in a message box
//************************************************** 
// The following statements deactivate and activate 
// the trace messages. You must uncomment the
// appropriate line.

// var DebugFlag = false;   // Trace output off
var DebugFlag = true;       // Trace output on

var j = 0;
debug("Start:", 0, 0);

for (var i = 1; i <= 10; i++)   // Loop 10 times.
{
    debug("Step: ", i, j);
    j = j + i;                  // Add all numbers.
}

debug("End:", i, j);

WScript.Echo("Result: ", j);

function debug(text, count, val)
{
    if (DebugFlag)          // Debug mode active?
        WScript.Echo(text, count, "Interim result: ", val);
}

//*** End

for...in Loop

You can use a for…in loop to access elements (properties of an object or items in an array). This loop uses the following syntax:

for (variable in [object | array])
{
    statements
}

The keyword in is followed by the name of a JScript collection object or of an array. The for loop assigns a reference to each item in the collection or array to the variable variable. The loop terminates after all elements are processed.

while Loop

A while loop is executed until a loop condition becomes false. A while loop uses the following syntax:

while (condition)
{ 
    statements
}

The condition is tested during each pass. If the condition is true, the statements within the { } block are executed. (As in the for loop, you can omit the braces if the loop contains only one statement.) The following sample uses a while loop:

var i = 0;

while (i <= 10)   // Try 10 passes.
{
    WScript.Echo ("Step: ", i);
    i++;                      // Increment index.
}

The program loops until the index is set to 11. Each pass shows the current index in a message box.

do...while Loop

A do...while loop is similar to a while loop. You can use a do...while loop to process a block of statements several times, until the condition becomes false. The following syntax is used:

do 
{ 
    statements 
} 
while (condition);

The condition in a do…while loop is tested at the loop's end. This means that the loop is executed at least once (even if the condition is false). If the condition is true, the statements within the { } block are executed again. (If the loop contains only one statement, you can omit the braces.)

The following code snippet (derived from the JScript Tutorial) uses this loop to process all drives of a Drives collection:

function GetDriveList()
{
    // Declare local variables.
    var fso, s, sharename, objDrives, drive;  
 
    // Use FileSystemObject.
    fso = new ActiveXObject("Scripting.FileSystemObject");

    // Get Drives collection.
    objDrives = new Enumerator(fso.Drives);  

    s = "";                   // Initialize result variable.
    do                        // The loop
    {
        drive = objDrives.item();            // Get item.
        s = s + drive.DriveLetter;           // Store drive letter
                                             // in result.
        s += " - ";
        if (drive.DriveType == 3)            // Shared drive?
            sharename = drive.ShareName;     // Use share name.
        else if (drive.IsReady)              // Local fixed drive?
            sharename = drive.VolumeName;    // Yes, use volume name.
        else
            sharename = "[Drive not ready]"; // Removable drive
        s +=  sharename + "\n";              // Add new line.
        objDrives.moveNext();                // Skip to next item.
    }
    while (!objDrives.atEnd());              // Test end condition.

    return(s);                // Terminate and return result.
}

switch Statement

You can use the switch statement to execute several blocks of statements based on the value of an expression. The statement has the following syntax:

switch (expression)
{
    case label :
        statements
    case label :
        statements
    
    default :
        statements
}

The expression is placed at the beginning of the construction. The first case branch that matches the expression is selected and the statements within the corresponding block are executed. (The label identifier is a placeholder for the value of the expression.) If no block matches the expression, the statements in the default branch are executed.

The following sequence uses the switch statement:

function Test(x) 
{
    switch (x)
    {
        case 1:
            
        case 2:
            
        case 3:
            
        default: 
            
    }
}

This code uses a variable x for the expression. If x = 1, the first branch, case 1:, is executed. If x = 2, the next branch is processed, and so on. Keep in mind that you must use a break statement (as you do in C) to prevent execution from falling through to the next branch.

break and continue Keywords

In JScript, you can use the optional break keyword to terminate a loop unconditionally. (The break keyword is similar to the Exit statement in VBScript.) If the interpreter detects this keyword, the current loop terminates and the code following the loop is executed.

The continue keyword has the opposite effect in a loop. If the interpreter detects this keyword, program control is immediately transferred to the beginning of the loop. The loop index is incremented or decremented, and the loop is executed again.