A variable is a fundamental part of any programming language. Variables are best visualized as a container. This is because a variable's purpose is to hold something - a value.
How does the variable get the value? You, as a programmer, assign the value to it. This value could be dynamically produced, depending on your program/script.
Once the variable has a value, you can use subsequent code to check its value, and do something (or not do something) depending on its value.
Some programming languages require that you declare your variable before assigning a value to it. Others (such as VBScript) make this optional. In any case, it is good practice to declare all your variables first.
Declare a VBScript Variable
VBScript variables are declared using the
<script type="text/vbscript"> Dim firstName Dim age </script>
These variables could also have been declared on the same line, separated by a comma:
<script type="text/vbscript"> Dim firstName, age </script>
As mentioned, it's good practice to declare all variables before using them. Occasionally, if you're in a hurry, you might forget to do this. Then, one day, you might misspell the variable name and all sorts of problems could start occurring with your script.
VBScript has a way of ensuring you declare all your variables. This is done with the Option Explicit statement:
<script type="text/vbscript"> Option Explicit Dim firstName Dim age </script>
Assign Values to your Variables
You assign values using an equals operator (equals sign). The variable name goes on the left, the value on the right.
<script type="text/vbscript"> Option Explicit Dim firstName Dim age firstName = "Borat" age = 25 </script>
Display your Variables
You can output the value of a variable by including it within the
<script type="text/vbscript"> Option Explicit Dim firstName Dim age firstName = "Borat" age = 25 document.write("Firstname: " & firstName & "</br />") document.write("Age: " & age) </script>
Display in Browser: