| << 4.1.4- Naming Conventions | Chapter4 | 4.2.1- Using Option Explicit >> |
Declaring Variables
We've got descriptions ofthe subtypes, and examples of how variables are used,but we missed an important step: how to declare a variable. Variables should bedeclared before they are used within a program, although when dealingwith loops, there are exceptions as we shall see. A variable declaration ismade with the keyword Dim, which is short for 'dimension'. This ratherodd-looking incantation tells the VBScript that you're setting up a newvariable. What this does is set aside the name and space for the variable inmemory. Until the variable is assigned a value, it contains nothing (bear inmind zero is a value, so it won't contain zero or even a blank space).
For example, the first line here declares a variable with thename CarType; the second line assigns a stringvalue to that variable:
Dim CarType
CarType = "Buick"
Declaring a variable in this way is known as explicit declaration, because we are explicitlytelling the computer what the name of our variable is, before we use it.
Many programming languages require you declare yourvariables explicitly, before you can use them. This isn't strictly necessary inVBScript: indeed, you can just as easily assign a value to a variable withouthaving first declared it. This process is known as implicitdeclaration of variables. As an example of implicit declaration, we can createanother variable, CarType2, and assign the valueto it, without using the Dim command:
CarType2 = "Pontiac"
It's generally good practice to explicitly declare avariable before you use it. This will allow you to keep track of all of thevariables in VBScript that you've created. In fact, many programmers declareall the variables they intend to use at the beginning of the code. It shouldhelp you to avoid creating unnecessary variables, as you won't be creating themon the off chance that you might need them later in the program. Further, youcan use explicit declaration together with the keywords OptionExplicit to help debug your programs.
| << 4.1.4- Naming Conventions | Chapter4 | 4.2.1- Using Option Explicit >> |

RSS

