"Dim x()" - Dynamic-Size Array Example

This section provides a tutorial example on how to declare a dynamic-size array 'Dim x()'. 'ReDim x(n)' statement must be used on to set the size of a dynamic-size array before it can be used.

We learned from previous sections that a dynamic-size array must be declared with a no size. For example, "Dim x()" declares a dynamic-size array, x, with no upper bound limit. You must set the size of x with a statement like "ReDim x(99)" before you can use it.

One important nature of a dynamic-size array is that it can be re-sized with a "ReDim Preserve x(n)" statement. The keyword "Preserve" is important, if you want to keep all old values in the array.

To show you how a dynamic-size array works, I wrote the following example, array_dynamic_size.html:

```<html>
<body>
<!-- array_dynamic_size.html
-->
<pre>
<script language="vbscript">
document.writeln("")
Dim aYear()
document.writeln("Check 1: Is aYear an array? " & IsArray(aYear))

'   aYear(0) = "Jan"   'Error 1: Subscription out of range

'   iSize = UBound(aYear)+1 'Error 2: Index out of range

ReDim aYear(5)
document.writeln("Check 2: Is aYear an array? " & IsArray(aYear))

aYear(0) = "Jan"
aYear(1) = "Feb"
aYear(5) = "Jun"

ReDim Preserve aYear(11)
aYear(10) = "Nov"
document.writeln("Months in a year:")
For i=LBound(aYear) To UBound(aYear)
document.writeln("   " & i & " = " & aYear(i))
Next
</script>
</pre>
</body>
</html>
```

Here is the output:

```Check 1: Is aYear an array? True
Check 2: Is aYear an array? True
Months in a year:
0 = Jan
1 = Feb
2 =
3 =
4 =
5 = Jun
6 =
7 =
8 =
9 =
10 = Nov
11 =
```

Note that:

• Output message "Check 1" shows that a dynamic-size array is an array event if its size is not set yet.
• Commented out "Error 2" shows that "UBound" can not be used is array's size is not set yet.