An alternative to sequential execution transfers the program flow to another part of your script. That is, instead of executing the next statement in the sequence, another statement is executed instead.
To make a script useful, this transfer of control must be done in a logical manner. Transfer of program control is based upon a decision, the result of which is a truth statement (returning a Boolean true or false). You create an expression, then test whether its result is true. There are two main kinds of program structures that accomplish this.
The first is the selection structure. You use it to specify alternate courses of program flow, creating a junction in your program (like a fork in a road). There are four selection structures available in JScript.
A third form of structured program flow is provided by exception handling, which is not covered in this document.
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 (or can be coerced to) true, the statement or block of statements after the if is executed.
// The smash() function is defined elsewhere in the code.
// Boolean test of whether newShip is true.
if( newShip )
smash(champagneBottle,bow);
// 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?";
}
// In this example, the test succeeds if either condition is true.
var theReaction = "";
if( (dayOfWeek == "Saturday") || (dayOfWeek == "Sunday") ){
theReaction = "I'm off to the beach!";
}
else{
theReaction = "Hi ho, hi ho, it's off to work I go!";
}
logical_expression ? alternative_1 : alternative_2
var hours = ""; // Code specifying that hours contains either the contents of theHour, or theHour - 12. hours += (theHour >= 12) ? " PM" : " AM";If you have several conditions to be tested together, and you know that one is more likely to pass or fail than the others, you can use a feature called 'short circuit evaluation' to speed the execution of your script. When JScript evaluates a logical expression, it only evaluates as many sub-expressions as required to get a result.
For example, if you have an AND expression such as ((x == 123) && (y == 42)), JScript first checks if x is 123. If it is not, the entire expression cannot be true, even if y is equal to 42. Hence, the test for y is never made, and JScript returns the value false.
Similarly, if only one of several conditions must be true (using the || operator), testing stops as soon as any one condition passes the test. This is effective if the conditions to be tested involve the execution of function calls or other complex expressions. With this in mind, when you write Or expressions, place the conditions most likely to be true first. When you write And expressions, place the conditions most likely to be false first.
A benefit of designing your script in this manner is that runsecond() will not be executed in the following example if runfirst() returns 0 or false.
if( (runfirst() == 0) || (runsecond() == 0) ) {
// some code
}
for(initialization;test;update) statement;Before each iteration of the loop, the condition is tested. If the test is successful, the code inside the loop is executed. If the test is unsuccessful, the code inside the loop is not executed, and the program continues on the first line of code immediately following the loop. 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. 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 be cautious 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 = 10; // Sets a limit of 10 on the loop.
var sum = new Array(howFar); // Creates an array called sum with 10 members, 0 through 9.
var theSum = 0;
sum[0] = 0;
for(var icount = 0; icount < howFar; icount++) { // Counts from 0 through 9 in this case.
theSum += icount;
sum[icount] = theSum;
}
var newSum = 0;
// This isn't executed at all, since icount is not greater than howFar
for(var icount = 0; icount > howFar; icount++) {
newSum += icount;
}
var sum = 0;
for(var icount = 0; icount >= 0; icount++) { // This is an infinite loop.
sum += icount;
}
// Create an object with some properties
var myObject = new Object();
myObject.name = "James";
myObject.age = "22";
myObject.phone = "555 1234";
// Enumerate (loop through)_all the properties in the object
for (prop in myObject)
{
// This displays "The property 'name' is James", etc.
WScript.Echo("The property '" + prop + "' is " + myObject[prop]);
}
The JScript for...in loop iterates over properties of JScript objects.
To loop over collections in JScript, you need to use the Enumerator object.
var x = 0;
while( (x != 42) && (x != null) ){
WScript.Echo("What is my favourite number?");
x = WScript.StdIn.ReadLine();
}
if( x == null )
WScript.Echo("You gave up!");
else
WScript.Echo("Yep - it's the Ultimate Answer!");
Note: Because while loops do not have explicit built-in counter variables, they are more vulnerable
to infinite looping than the other types of loops. Moreover, because it is not necessarily easy to discover where or
when the loop condition is updated, it is easy to write a while loop in which the condition never gets updated. For this
reason, you should be careful when you design while loops.
var x = 0;
do{
WScript.Echo("What is my favourite number?");
x = WScript.StdIn.ReadLine();
} while ((x != 42) && (x != null));
if( x == null )
WScript.Echo("You gave up!");
else
WScript.Echo("Yep - it's the Ultimate Answer!");
The following example builds on the previous example to use the break and continue statements to control the loop.
var x = 0;
do{
WScript.Echo("What is my favourite number?");
x = WScript.StdIn.ReadLine();
// Did the user cancel? If so, break out of the loop
if( x == null ) break;
// Did they enter a number?
// If so, no need to ask them to enter a number.
if( Number(x) == x ) continue;
// Ask user to only enter in numbers
WScript.Echo("Please only enter in numbers!");
} while (x != 42)
if( x == null )
WScript.Echo("You gave up!");
else
WScript.Echo("Yep - it's the Ultimate Answer!");
function function_name([param1, param2, param3])
{
statement_1;
statement_2;
...
last_statement;
}
Use keyword return if a function needs to return a value. The following function prints some
information about the script that calls it:
function PrintScriptInfo()
{
WScript.Echo("Script name:", WScript.ScriptName);
WScript.Echo("Script full name:", WScript.ScriptFullName);
var args = WScript.Arguments;
for(i=0;i<args.length;i++)
WScript.Echo(args.Item(i));
}