Initializing Variables

Microsoft® Windows® 2000 Scripting Guide

Initializing a variable simply means assigning a beginning (initial) value to that variable. For example, the following lines of code initialize two variables, setting the value of X to 100 and the value of Y to abcde:

X = 100
Y = "abcde"

If you create a variable but do not initialize it (that is, you do not assign it a value), the variable will take on one of two default values:

  • If the variable is used as a string, the value will be Empty.

  • If the variable is used as a number, the value will be 0.

For example, the following script creates two variables (X and Y), but does not initialize either variable:

Dim X
Dim Y
Wscript.Echo X & Y
Wscript.Echo X + Y

In line 3 of the script, the two variables are used as strings. (The & operator is used to combine two strings.) When this line runs, the message box shown in Figure 2.8 appears. Because the two variables are Empty, combining the two strings means combining nothing with nothing. As a result, the message box displays an empty string.

Figure 2.8 Combining Two Uninitialized Variables


In line 4 of the script, the two variables are used as numbers. Numeric variables that have not been initialized are automatically assigned the value 0. Thus, this line of the script echoes the sum of 0 + 0, as shown in Figure 2.9.

Figure 2.9 Adding Two Uninitialized Variables


Using the Equals Sign in VBScript

In VBScript, the equals sign (=) has a subtly different meaning than it does in arithmetic. In arithmetic, the equation X = 2 + 2 is read:

"X equals 2 plus 2."

In VBScript, however, this same statement is read:

"X is assigned the value of 2 plus 2."

In the preceding example, there is not much difference; either way, X gets assigned the value 4. But consider the following script, which uses a loop to count from 1 to 10:

For i = 1 to 10
    X = X + 1

The second line in this script would appear to be a mathematical impossibility: How can X be equal to X plus 1? The reason why this is a perfectly valid VBScript statement is that it is not an example of a mathematical equation but is instead an example of a variable (X) being assigned a new value. The statement is actually read:

"X is assigned the current value of X plus 1."

In other words, if X is currently 3, when this statement runs X will be assigned the value 4, that is, 3 (the current value) plus 1.

The fact that the equals sign is actually an assignment sign is also useful in constructing strings. For example, the following script constructs a message from multiple string values:

Message = "This "
Message = Message & "is a "
Message = Message & "test message."
Wscript.Echo Message

When the script runs, the message box shown in Figure 2.10 appears.

Figure 2.10 Concatenated Message