Search this site...

Working with Variables in ASP

What is a variable?

A variable is a qualified name to a specific part of computer's memory. "Qualified" means the name of the variable must be legal in VBScript. Like other programming languages, you cannot name your variable to be one of the reserved words in that language. With variables, we can change and store data values. Without variables, we would only be able to display results; we won't be able to store the results for future use.

Syntax requirements for variables

There are number of syntax requirements for variables. First, as discussed earlier, reserved keywords of the language cannot be used as variable names because reserved words have special meaning in the language. For example, DIM indicates to the script-processor that variable(s) are about to be declared. If a programmer attempts to declare a variable with the same name as a reserved keyword, an error will occur. Secondly, a variable name must not contain spaces, periods, or dashes. For example, the following are not valid variable names:

This is my variable 'because of spaces
This.is.my.variable 'because of periods
This-is-my-variable 'because of dashes

If a variable name is long, then, use underscores or mixture of uppercase and lowercase letters as

This_is_my_variable 'using underscores at word breaks
ThisIsMyVariable 'using uppercase at beginning of each word

Lastly, a variable name must begin only with a letter not other characters or numbers. The following are not valid variable names:

1_This_is_my_variable 'because of 1
_ThisIsMyVariable 'because of _
^_ThisIsMyVariable 'because of ^ and _

Although variable names should be meaningful, their names length should not be longer than 255 characters. The ASP engine will ignore the characters after the 256th character in the variable name. Hopefully, naming conventions from the next section will help you to name our variables in more meaningful way.

Variable naming conventions

In the previous section, we covered the rules for variable names and these rules must be followed to avoid errors. In comparison, naming conventions are not required by the language but rather are helpful to the programmer and to others who will look at the code. Because VBScript determines from the context the type of the variables, the programmer should use the data type prefix in the name.

Another important guideline for naming variables is that the variable names should be descriptive. For example, x as a variable name is a poor naming choice unless it represents x-coordinate values. Even better yet, a variable for representing x-coordinates should be named as xCoordinate or x_ coordinate instead of just x. Using meaningful names for variables help not only others to easily understand the code but also the programmer, especially when reviewing it a year from now.

An example of working with variables

Before a variable can be used, it needs to be declared either explicitly (by the programmer) or implicitly (by the computer). A variable declaration simply refers to the process of allocating memory to the variable.

We explicitly declare a variable with the keyword DIM and then the variable name. For instance, DIM x declares a variable named x. You can also declare more than one variable per line, make sure each variable name is separated with a comma:

Dim x, y, z, h

The following shows an example.

  1. <html>
  2. <title> Variables </title>
  3. <body>
  4. <%
  5. DIM five, result
  6. Five = 5
  7. response.write "The value of variable Five is "
  8. response.write five
  9. result = five + five
  10. response.write "<br>"
  11. response.write "The value of variable result is "
  12. response.write result
  13. %>
  14. </body>
  15. </html>
Listing 1 working with variables

We declare a variable named five by placing the variable name after the reserved keyword "DIM" on line 4. Note that we cannot declare a variable named DIM because this is a reserved keyword in VBScript. Similarly, we next declare the variable result on line 5. We could have declared both of these variables on one line as:

DIM five, result

Remember declaring multiple variables on one line without separating them with commas i.e., DIM five result, is a syntax error.

On line 6 in Listing 1, we assign the value 5 to the variable five. "Assign" means setting the value to the left hand side of the equal sign (also called assignment operator) with what is on the right hand side. To confirm this assignment, we print the value of five by using the response.write object on line 8. Because we want to print the value of a variable, variable name (in this case, five) is not included in double quotation marks. The lines response.write "The value of variable Five is " and response.write five print "The value of variable Five is 5".

The next line result = five + five adds the variable five to the variable five, obtaining 10. The result variable is assigned the value 10 with the assignment operator. Next, on line 10 we print a new line using the HTML tag for a new line Response.Write "<br>" enclosed in double quotation marks. This means the next output on the browser will be printed on a new line instead of on the same line. Note that HTML tags must be enclosed with double quotations marks when using response.write object.

Figure 1 working with variables
Figure 1 working with variables

Similar to lines 7 and 8, lines 11 and 12 print the value of variable result is 10. Finally, we close the ASP script tag on line 13. Figure 1 shows the output.

Constant variables

A constant is a variable whose value is not changed by the execution of the program. Most of the time, a program is written to modify the values of a variable. In some cases, however; we want to use the same value throughout the program. Examples are tax rate, hours in a day, etc. If our program was calculating a total sales amount owed by a customer, we would add the sales amount plus the current tax rate. We know that the sales amount is likely to vary because each customer would buy something different but the tax rate is likely to be the same for all taxable purchases. We could represent the tax rate as a constant because tax rate won't change frequently. If the tax rate did change, we could just set its old value with the current value. A constant variable means that its value will not be changed while the program is running. By the way, constant variables are capitalized to convey that they are constants.

We would declare a variable to represent tax rate as a constant by the following:

const TAXRATE = .05

Notice that we do not use the reserved keyword DIM before const. See the following example that uses a constant variable:

const TAXRATE = .05
DIM intItems, fltCostPerItm, fltAmtBeforeTaxes, fltTotal, sout
intItems = 10
fltCostPerItm = 2.69
fltAmtBeforeTaxes = intItems * fltCostPerItm
fltTotal = (fltAmtBeforeTaxes * TAXRATE) + fltAmtBeforeTaxes
sout = "Cost Per item: $ " & fltCostPerItm & "<br>"
sout = sout & "Number of items bought: " & intItems & "<br>"
sout = sout & "Total Before Taxes: $ " & fltAmtBeforeTaxes & "<br>"
sout = sout & "Total after taxes: $ " & round (fltTotal, 2)
response.write sout

We declare and assign a value to the variable TAXRATE on line 1 above. After a value has been assigned to a constant variable, its value cannot be changed later in the program. In our example, we cannot change the value of TAXRATE after line 1; for instance, this won't work if you had this code after line 1:

TAXRATE = .07

You will get an "Illegal assignment: 'TAXRATE'" error if you update the value of the constant. The rational behind using constant variables is to assign a value once and use it as many times needed without changing its value while the program is running. If you did have to change the value of a constant variable, you will update the value only at one place versus using a no variable at all, in which case, you may end up updating the value on many places. The following shows the output of the above code:

Cost Per item: $ 2.69
Number of items bought: 10
Total Before Taxes: $ 26.9
Total after taxes: $ 28.24

In summary, a constant variable should be used whenever a variable's value won't be changed while the program is running. A constant variable has a global scope, meaning a constant variable can be accessed anywhere in the same program.

Scope and life of a variable

The scope of a variable refers to the availability of the variable through out the program. A variable declared in one file is not necessarily available in another file. Even within the same program, a variable in one function cannot be visible anywhere else in the program. When we declare a variable, it literally comes to life when we execute the program that contains the declared variable. It is up to the programmer whether to use the declared variable or not. The variable will die or its availability will cease to exist once the program ends or its scope expires. Variables declared inside of blocks such as private functions, or subroutines are not visible outside of the block. Consider the following example:

const TAXRATE = .05
dim str
str = "A string value." & " TAXRATE " & TAXRATE
ShowScope
sub ShowScope ()
dim str
str = "In ShowScope ()" & " TAXRATE " & TAXRATE
response.write str & "<br>"
end sub response.write str

In this example, we have declared two variables with the same name (str) see lines 2 and 6. On line 3, we assign a string value to this variable. Line 4 calls our subroutine. Inside the ShowScope () subroutine we declare the variable str and assign a value (see lines 6 and 7). Line 8 prints the value of this variable; note the value of this variable would be different than the value assigned outside of the subroutine (see line 3 above). Because the variables inside a block (such as subroutines, functions) have only block-scope, the value of those variables will not be available outside of that block. This is why the print statement on the last line in our code above will print "A string value." & " TAXRATE " & TAXRATE but not "In ShowScope ()" & " TAXRATE " & TAXRATE. The following shows the output of the above code:

In ShowScope () TAXRATE 0.05
A string value. TAXRATE 0.05