[Previous] [Table of Contents] [Next]

The Structure of a JScript Program

If you've used JScript or JavaScript in HTML documents, you'll notice that JScript programs for WSH are different. First, JScript programs for WSH contain no HTML tags. The entire script is stored in a .js file. Listing 5-1 is a typical JScript program. (This file, like the other code samples shown in this chapter, is in the \WSHDevGuide\Chapter05 folder on the book's companion CD.)

Listing 5-1 OKCancel.js

//************************************************
// File:   OKCancel.js   (WSH Sample in JScript)
// Author: (c) G. Born
// WSH script creating an OK/Cancel dialog box
//************************************************
 
var mbOKCancel = 1;       // Declare variable.
var mbInformation = 64;
var mbCancel = 2;

var Text  = "Test sample";
var Title = "Born's Windows Script Host sample";

var WshShell = WScript.CreateObject("WScript.Shell");
var intDoIt =  WshShell.Popup(Text,
                              0,
                              Title,
                              mbOKCancel + mbInformation);
if (intDoIt == mbCancel) 
{
    WScript.Quit();
}

WScript.Echo("Sample executed");

//*** End

Unlike a JScript program in an HTML document, a WSH script needs no event handling.

Comments

If you want the interpreter not to interpret a line or part of a line in your code, you can mark it as a comment. Comments in JScript begin with two forward slashes, as shown here:

// This is a comment.
WScript.Quit();   // Terminate script.

The comment can appear on its own line or can be appended to an executable statement (as shown in the second line above). When the interpreter finds a comment, it ignores the rest of the line.

NOTE
JScript also supports multiple-line comments in the format /* … */. I don't use that format in this book, however.

Statements

You must enter JScript statements according to the JScript syntax rules, which differ in a few significant ways from the syntax rules of VBScript and other languages.

IMPORTANT
Keywords, function names, and variable names in JScript are case sensitive, so you must be careful how you write a statement. For example, res = Test(); and res = test(); are different. Beginners often overlook case sensitivity and create syntax errors.

It's a good programming practice to close statements with a semicolon (except statements in front of the closing brace of a code block or control statements such as if and do). To simplify the code, you can terminate every statement with a semicolon. The following lines are valid JScript statements:

value = 10;
value = value + 10;
Tax = 0.1;

Continued lines

Unlike VBScript, JScript doesn't have a special character for marking statements that span several lines because the semicolon identifies the end of a valid statement, as shown here:

WScript.Echo("Hello",
             "I was here");

If a statement contains a string, the line break must not be within the string. You can break the string into several substrings and concatenate the substrings by using the + sign.

Using several statements per line

As you learned in Chapter 4, you use a colon to separate several statements on a line in VBScript. In JScript, you use a comma or a semicolon, as shown in the following code sequence, which creates a message box showing the value 35:

var x = 15, y = 20;
WScript.Echo(x + y); WScript.Echo("Done");

To keep your code transparent and more readable, however, I recommend that you avoid this construction. Or can you immediately understand the following line?

for (var i = 0; i <= 10; i++, j++)

In this code, I used a comma within the loop to increment the variable j for each pass. It's easy to move the statement to increment the variable j in the body of the loop.

Constants

Constants are numbers or strings in a JScript statement. You can define constants in the following ways in JScript:

Result = 15 + 10;
Name = "Born";
Pi = 3.14;

The first line contains the constants 15 and 10, which are added. The result is assigned to the variable Result. The second line assigns a string constant "Born" to a variable. The last line contains a constant with the value 3.14.

JScript doesn't use predefined constants, as VBScript does. If you want to use symbolic constants (such as vbOKOnly) in your scripts, you must declare them as variables. I'll use this technique in upcoming samples to improve the readability of the source code.

Variables

In JScript, you can use variables to store values in memory and identify them with a name. You must declare a variable before it is used for the first time. The declaration can be implicit, using an assignment statement, or it can be explicit, using the var statement. The following code declares a variable implicitly:

Price = 17;
Tax = 16;

It's better programming practice to declare a variable explicitly, using the var statement, as shown here:

var text;     // Declare a variable without assigning a value.
var x = 19;   // Declare a variable and set its value.
var Price = 19;
var y = Math.sin(x);
var text2 = "Value ";

The first statement declares a variable. (Its value is undefined, however.) The other lines contain variable declarations with assignment statements that define each variable's value and type.

Variable scope

Why should you declare a variable using the var statement if it's sufficient to use the variable name in an assignment statement? Because the type of declaration influences the scope of a variable, and the scope determines where you can access the variable. The rules are as follows:

I recommend using the var statement to declare a variable within a function because the variable's scope is restricted to the function level. If you need a global variable or pseudoconstant, you can declare it using a var statement in the script's header. This improves readability and makes your script programs easier to maintain.

Variable names

You should follow these rules and guidelines when choosing variable names in JScript:

If you declare a variable without assigning a value, the interpreter creates the variable in memory but the value is set to undefined. Using such an uninitialized variable on the right side of an assignment statement, as shown here, causes trouble:

var factor;                  // Value still undefined.
var Price = 100 * factor;    // Price is set to "NaN."

The value of the first variable, factor, is still undefined, so the interpreter assigns the value NaN to the variable Price. (NaN stands for "Not a Number.") The result, Price, in the second statement is also undefined.

When you declare a variable, you can assign the value null or any other value:

var fact1 = null;            // Assign a special value null.
var note = 3 * fact1;        // Value is set to 0.

Initializing your variables before you use them is good programming practice. If you don't, you run the risk of introducing undefined values into your calculations, as in the following code sequence:

var first_name = "Born";        // Initialized variable 
var last_name;                  // Uninitialized variable
var aMess = first_name + " " + last_name;

WScript.Echo(aMess);            // Displays "Born undefined"

You also risk causing run-time errors, as in the following code sequence:

last_name = "";                     // Implicit variable declaration 
var aMess = last_name + first_name; // first_name still undefined

The second line causes a run-time error because the variable, first_name, is still undefined.

Data types

JScript variables don't have a fixed data type. The language uses a Variant data type, so you can't define an explicit data type when you declare a variable. The Variant data type keeps variable values in the required format (numbers, strings, dates, and so on). The JScript interpreter uses an implicit type conversion when performing operations on values that have different types. For example, to embed a number in a string, you could use an expression such as "Text" + 99; JScript implicitly converts the number 99 to the string "99" and then concatenates the two strings to form "Text99". If you want to assign a string such as "99" to a numeric value, you must use the type conversion functions parseInt and parseFloat.

The following code uses implicit type conversion to assign a numeric variable to a string:

var from = 1;
var to = 10;
var action = "Count from ";
action += from + " to " + to + ".";

This code sets the variable action to the string "Count from 1 to 10." The numeric values are converted to strings.

The following code sequence (which is taken from the JScript Language Reference) assigns the value 0110 to the variable x:

var x = 0;
x += 1 + "10";

This code is really tricky—too tricky to use in your programs if you want your code to be readable. The expression 1 + "10" on the right side of the assignment statement concatenates a numeric value with a string. The JScript interpreter converts the numeric value 1 to the string "1" and returns the string "110". The string is then assigned to the variable x. The assignment operator is preceded by a + character, which forces the new value to be added to the value contained in the variable x. The variable x contains the numeric value 0 set in the first line. To add the string evaluated on the right side of the assignment, the current value of x is converted to the string "0". Then the value "0" is concatenated with "110" using the += operator. The result is "0110".

Data subtypes

JScript uses only a few subtypes for variables and constants:

For a more detailed discussion of data types, see the JScript Tutorial.

Escape Sequences in Strings

Some characters on the keyboard, such as Backspace and Enter, are impossible to type directly into a string. Other characters, such as the single and double quotes, won't work in a string because single and double quotes already are reserved to indicate the beginning or end of a string. Fortunately, JScript allows you to embed these characters in a string by using a special combination of characters called an escape sequence. Table 5-1 lists the escape sequences for JScript strings.

Table 5-1 Escape Sequences

Escape SequenceMeaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Tab
\' Single quote
\" Double quote
\\ Backslash

The backslash character is used as an escape character; the character following it is inserted into the string. Therefore, to insert a backslash into a string, you must use a double backslash. (The double backslash is important, for example, if a string contains a path definition.) The string "C:\name" won't result in a valid pathname in JScript because \n is interpreted as "new line." You must write "C:\\name" instead. You can use \n\r (the equivalent of vbCrLf in VBScript) in a string to format the output to a message box. To insert a single quote or double quotes into a string, you must write \' or \".

The following statement causes a run-time error:

Text = "He says: "WSH is cool!""

The interpreter recognizes two strings and a constant that can't be resolved. To insert a double quote into the string, you must write the statement as follows:

Text = "He says: \"WSH is cool!\""

The interpreter detects the \" sequence and inserts the double quote.