Variables are automatically declared in VBScript as Variant data types. There is no strict type-casting. This means that one does not have to explicitly declare a variable as being of type Integer for instance. To enforce explicit declaration of variables within a web page use the Option Explicit command on the first line of a web page. Use of Option Explicit is recommended.
For x = 0 to 5 document.write x & "<BR>" Next
Dim x For x = 0 to 5 document.write x & "<BR>" Next
Variables can be declared on the same line.
Dim x, y, z
Variables are declared explicity using the Dim, Public or Private statements. The ReDim statement is used for the declaration of dynamic arrays where subsequent ReDim statements can resize that dynamic array.
A variable exists within its scope. Thus a variable declared within a procedure exists whilst that procedure is running. A variable declared globally within a web page exists for the time that the web page is active. Thus a variable of the same name can be used within different procedures without danger of conflict.
An array variable is a variable which contains multiple items. Below is a single dimensional array containing 11 elements.
The number shown in parentheses is 10. However, as in many scripting and programming languages, arrays are zero-based. This means that the first element is referenced as A(0) and not A(1). The array shown above is a fixed size array. This array has a fixed or pre-declared number of elements. Assigning values to these array elements is as shown below.
A(0) = 433 A(1) = 145 ... A(10) = 1000
Arrays can have more than a single dimension. In fact VBScript will allow arrays of upto 60 dimensions. Generally 3 or 4 dimensions is a practical limit. For instance, the array shown below has 4 rows and 12 columns.
Dim anArray(4, 12)
Arrays can also be delared dynamically. This means that the number of elements changes whilst the script is running.
Dim anArray() ReDim anotherArray()
A ReDim statement must be used to subsequently determine the number of dimensions and the size of each dimension. In the example below the initial size of the array is set to 10. The second ReDim statement resizes the array to 15. The Preserve keyword can also be used to preserve the contents of the first array whilst the resizing occurs.
ReDim anArray(10) ... ReDim Preserve anArray(15)
It stands to reason that resizing an array smaller means a loss of the exceeded elements.
The keyword Const is used to declare constant values. As opposed to a variable a constant can not be changed.
Const PI PI = 3.142