Using Variables and Constants

A variable is a named storage location in the computer's memory that contains data, such as a number or a text string. The data contained in a variable is called the variable's value. Variables give you a way to store, retrieve, and manipulate values using names that help you understand what the script does.

Declaring and Naming Variables

Follow the rules and guidelines of your scripting language for naming and declaring variables. Even if you are not required to declare a variable before using it, it is a good habit to develop because it helps prevent errors. Declaring a variable means telling the script engine that a variable with a particular name exists so that you can use references to the variable throughout a script.

VBScript

VBScript does not require variable declarations, but it is good scripting practice to declare all variables before using them. To declare a variable in VBScript, use the Dim, Public, or Private statement. For example:

  <% Dim UserName %>

You can use the VBScript Option Explicit statement in an .asp file to require variables to be explicitly declared with the Dim, Private, Public, and ReDim statements. The Option Explicit statement must appear after any ASP directives and before any HTML text or script commands. This statement only affects ASP commands that are written in VBScript; it has no effect on JScript commands.

  <% Option Explicit %>
<HTML>
<%
  Dim strUserName
  Public lngAccountNumber
%>
.
.
.

For more information about these commands, see the VBScript Language Reference, which can be found at the Microsoft Script Technologies Web site.

JScript

Although JScript does not usually require variable declarations, it is good scripting practice to declare all variables before using them. To declare a variable, use the var statement. For example:

  <% var UserName %>

Typically, you will only need to declare a variable in JScript when you need to distinguish a variable inside a function from a global variable used outside the function. In this case, if you do not distinguish between the two variables, JScript will assume that that you referring exclusively to the global variable. For more information on the var statement, see the JScript Language Reference. You can find this reference at the Microsoft Script Technologies Web site.

Variable Scope

The scope, or lifetime, of a variable determines which script commands can access a variable. A variable declared inside a procedure has local scope; the variable is created and destroyed every time the procedure is executed. It cannot be accessed by anything outside the procedure. A variable declared outside a procedure has global scope; its value is accessible and modifiable by any script command on an ASP page.

note Note Limiting variable scope to a procedure will enhance performance.

If you declare variables, a local variable and a global variable can have the same name. Modifying the value of one will not modify the value of the other. If you do not declare variables, however, you might inadvertently modify the value of a global variable. For example, the following script commands return the value 1 even though there are two variables named Y:

  <%
  Option Explicit 
  Dim Y

  Y = 1

  SetLocalVariable

  Response.Write Y

Sub SetLocalVariable
    Dim Y
    Y = 2
End Sub
%>

The following script commands, on the other hand, return the value 2 because the variables are not explicitly declared. When the procedure call sets Y to 2, the scripting engine assumes the procedure intended to modify the global variable:

  <% 
  Option Explicit
  Dim Y = 1

  SetLocalVariable

  Response.Write Y

Sub SetLocalVariable
    Y = 2
End Sub
%>

To avoid problems, develop the habit of explicitly declaring all variables. This is particularly important if you use the #include statement to include files into your .asp file. The included script is contained in a separate file but is treated as though it were part of the including file. It is easy to forget that you must use different names for variables used in the main script and in the included script unless you declare the variables.

Giving Variables Session or Application Scope

Global variables are accessible only in a single .asp file. To make a variable accessible beyond a single page, give the variable either session or application scope. Session-scoped variables are available to all pages in one ASP application that are requested by one user. Application-scoped variables are available to all pages in one ASP application that are requested by any user. Session variables are a good way to store information for a single user, such as preferences or the user's name or identification. Application variables are a good way to store information for all users of a particular application, such as an application-specific greeting or general values needed by the application.

ASP provides two built-in objects into which you can store variables: the Session object and the Application object.

You can also create object instances with session or application scope. For more information, see Setting Object Scope.

Session Scope

To give a variable session scope, store it in the Session object by assigning a value to a named entry in the object. For example, the following commands store two new variables in the Session object:

  <% 
  Session("FirstName") = "Jeff"
  Session("LastName") = "Smith" 
%>

To retrieve information from the Session object, access the named entry by using the output directive (<%=) or Response.Write. The following example uses the output directive to display the current value of Session("FirstName"):

  Welcome <%= Session("FirstName") %>

You can store user preferences in the Session object, and then access those preferences to determine what page to return to the user. For example, you can allow a user to specify a text-only version of your content in the first page of the application and apply this choice on all subsequent pages that the user visits in this application.

  <%
  strScreenResolution = Session("ScreenResolution")
  If strScreenResolution = "Low" Then
%> 
  This is the text version of the page.
<% Else %> 
  This is the multimedia version of the page.
<% End If %>

note Note If you refer to a session-scoped variable more than once in a script, consider assigning it to a local variable, as in the previous example, to improve performance.

Application Scope

To give a variable application scope, store it in the Application object by assigning a value to a named entry in the object. For example, the following command stores an application-specific greeting in the Application object:

  <% Application("Greeting") = "Welcome to the Sales Department!" %>

To retrieve information from the Application object, use the ASP output directive (<%=) or Response.Write to access the named entry from any subsequent page in the application. The following example uses the output directive to display the value of Application("Greeting"):

  <%= Application("Greeting") %>

Again, if your script repeatedly refers to an application-scoped variable, you should assign it to a local variable to improve performance.

Using Constants

A constant is a name that takes the place of a number or string. Some of the base components provided with ASP, such as ActiveX Data Objects (ADO), define constants that you can use in your scripts. A component can declare constants in a component type library, a file that contains information about objects and types supported by an COM component. Once you have declared a type library in your .asp file you can use the defined constants in any scripts in the same .asp file. Likewise, you can declare a type library in your Global.asa file to use the defined constants in any .asp file in an application.

To declare a type library, use the <METADATA> tag in your .asp file or Global.asa file. For example, to declare the ADO type library, use the following statements:

  <!--METADATA NAME="Microsoft ActiveX Data Objects 2.5 Library" TYPE="TypeLib" UUID="{00000205-0000-0010-8000-00AA006D2EA4}"-->

Or, rather than referring to the type library's universal unique indentifier (UUID), you can also refer to the type library by file path:

  <!-- METADATA TYPE="typelib" FILE="c:\program files\common files\system\ado\msado15.dll"-->

You can then use ADO constants in the .asp file where you declared the type library, or in an .asp file residing to an application containing a Global.asa file with the ADO type library declaration. In the following example, adOpenKeyset and adLockOptimistic are ADO constants:

  <%
  'Create and Open Recordset Object.
  Set rstCustomerList = Server.CreateObject("ADODB.Recordset")

  rstCustomerList.ActiveConnection = cnnPubs
  rstCustomerList.CursorType = adOpenKeyset
  rstCustomerList.LockType = adLockOptimistic
%>

The following table lists commonly used type libraries and UUIDs:

Type Library UUID
Microsoft ActiveX Data Objects 2.5 Library {00000205-0000-0010-8000-00AA006D2EA4}
Microsoft CDO 1.2 Library for Windows 2000 Server {0E064ADD-9D99-11D0-ABE5-00AA0064D470}
MSWC Advertisement Rotator Object Library {090ACFA1-1580-11D1-8AC0-00C0F00910F9}
MSWC IIS Log Object Library {B758F2F9-A3D6-11D1-8B9C-080009DCC2FA}

For reference information about the <METADATA> tag, see TypeLibrary Declarations.

In previous versions of ASP, some components provided constant definitions in files that had to be included in each ASP file that used those constants. The use of the #include directive to include constant definitions is still supported, but type libraries are generally easier to use and make your scripts more easily upgraded. Components might not provide constant definition files in future releases of ASP.

note Note Using the <METADATA> tag rather than the #include directive may improve the performance of your Web application.

You can define your own constants. In VBScript, use the Const statement. In JScript, you can the var statement to assign a constant value to variable. If you want to use your constants on more than one .asp file, put the definitions in a separate file and include them in each .asp file that uses the constants.