Tuesday, April 5, 2011

Basic Programming Constructs

Declaring Your Variables

A variable is a name assigned to a location in a computer's memory to store data. Before you use a variable in a VBScript program, you should declare its name. Variables are declared with the dim keyword, like this:

dim x
dim y
dim sum

You can also declare multiple variables with the same dim keyword.

dim x, y, sum

The initial value of the variable is empty, a special value in VBScript.
Dim is short for dimension. When you declare a variable the interpreter needs to allocate memory to hold the contents for you. In strongly typed languages (which VBScript is not) the interpreter or compiler will know what the dimension (size of memory) is required to hold the value is based on the data type. In VBScript no memory is allocated until you store a value in the variable.

Types of Variables

A big difference between VBScript and other languages like Visual Basic and C is that VBScript is untyped. This means that a VBScript variable can hold a value of any data type, and its data type does not have to be set when declaring the variable. This allows you to change the data type of a variable during the execution of your program, for example:

dim x
x = 10
x = "ten"

In this example the variable x is first assigned the integer value of 10, and then the string value of the word ten.

Using Operators

Operators are the things that act on variables. We have already seen an operator used in the previous example, where we were assigning values to our variables.

The example used one of the most common operators, "=" or the assignment operator. Another operator would be the addition operator "+".

dim x, y, sum
x = 1: y = 3: sum = 0
sum = x + y

This small chunk of VBScript code will declare the variables x, y and sum and assign the number 1 to x, 3 to y and 0 to sum. The next line of the script will add x to y and assign it to sum. The value of the sum variable will be 4.
Other operators are used to compare things, i.e. "=" equality, ">" greater than.
For example,

if ( sum = 0 ) then
sum = x + y
end if

This bit of code first checks to see if sum is equal to zero, and if so then it adds x and y together and assigns the result to sum. The "if" statement is an example of a control structure which we will examine in next article.


  1. I'm trying to get this code works in this website :webcheatsheet.com/tryit/index.php?section=asp&example=loops_1

    scr1pt type="text/vbscript"
    For i = 0 to 10
    document.write("Title " & i & "")
    document.write("< iput type=radio name=radio"&i + 1&" value="&i + 1&" />")

    How come it didn;t work? Please let me know if this code is correct. Thanks!

    1. sorry for the late reply , Use Response.Write in place of Document.write