A Closer Look at Variables

Let's take a closer look at variables. Remember that I said that a variable is a piece of reserved memory? Well, how does the computer know how large to make thiat piece of memory? Luckily, this is something that's handled automatically by the VBScript engine. You don't really have to worry too much about it. However, it's useful to know that the VBScript engine will dynamically change and reallocate the actual memory address that are used up by variable. For example, take a look at this variable program:

'Declare the variable
Dim SomeText
'Initialize the variable
SomeText = "Hello there."
MsgBox SomeText
'Change the value of the variable
SomeText = "This is longer text which takes up more space in memory."
MsgBox SomeText
'Change it again
SomeText = "Shorter this time."
MsgBox SomeText

This is bit of an oversimplification, but what happens here is that when we declare the variable, the script engine that is executing the script allocates a very minimal amount os memory. Since there's nothing stored in the variable yet, it doesn't require much space. When we initialize the variable with the simple text "Hello there," the script engine asks the computer for a little more space in memory to store this new value - but just enough to hold this short phrase. Then, when we assign the much longer text to the same variable, the script engine must allocate even more memory. Finally, when we assign the shorter string of text, the script engine can reduce the size of the variable in memory.