ASP Language Basics

Active Server Pages (ASP) is a proven, well-established technology for building dynamic Web applications, which provides the power and flexibility you need to create anything from a personal, Web based photo gallery to a complete catalogue and shopping cart system for your next eCommerce project. One unique feature of ASP is that it lets you choose your favourite scripting language, be it JavaScript or VBScript; however, VBScript is by far the most popular choice. In this article, I’ll bring you up to speed on the basic syntax of the VBScript language, including variables, operators, and control structures.

This article is the second in a series teaching ASP. Specifically, the goal of this series is to teach you all you need to know to create dynamic Web sites using ASP. This article picks up right where the previous article in the series, Getting Started with ASP, left off.

Variables

Here is the listing for the first ASP script I helped you create in the previous article:

1  <html> 
2  <head>
3  <title> My First ASP Page </title>
4  </head>
5  <body>
6  <%
7  ' Write out a simple HTML paragraph
8  Response.Write "<p>This is a test of ASP.</p>"
9  %>
10 </body>
11 </html>

As I admitted in that article, this is a pretty uninteresting example of an ASP script. When it comes right down to it, this script doesn’t do anything a plain, old HTML page couldn’t do. Oh sure, I gave a slightly more interesting example that displayed the current server time, but to be really useful a script needs to perform some form of calculation, or manipulate dynamic information to present it in some interesting way.

The language used for writing most ASP programs, and which I’ll be using throughout this series, is called VBScript. Like most programming languages, VBScript lets you store data in variables. A variable may be thought of simply as a named location in memory where data may be stored. VBScript is what is known as a loosely typed language, which means that a particular variable may store any kind of information, be it a number, a piece of text, a date, or some more complicated chunk of data (as opposed to strictly typed languages where you can only store one kind of information in each variable). Before you can use a variable, though, you must declare it; that is, you must let ASP know that you want to create a variable with a particular name.

Let’s look at a basic example to help solidify these concepts in your mind. Say you were writing a Web page that performed conversions between Celsius and Fahrenheit temperatures. In countries where Celsius is used, 20&deg;C is commonly accepted as the value for room temperature. The following code creates a variable called intRoomTempC, and then assigns it a value of 20:

Dim intRoomTempC     ' Create a variable 
intRoomTempC = 20    ' Assign the variable a value of 20

The keyword Dim in the above is short for dimension, and is used to tell VBScript to create a variable with the name specified (in this case, intRoomTempC). Why ‘dimension’, you ask? I agree, it’s not the most obvious choice, but basically it refers to what you’re asking VBScript to do. When creating a variable, VBScript needs to assign some space in memory to store whatever value(s) will be placed in the variable, and part of that task is to figure out the size (dimension) of the space that needs to be allocated. In any case, creating a variable is as simple as typing Dim followed by the name of the variable.

The second line of the above example assigns a value to the variable that was just created; specifically, it stores the number 20 in the variable. The equals sign (=) is called the assignment operator because it is used to assign values to variables. During the course of this article, you’ll meet many other operators that do other weird and wonderful things to variables and the values they store.

You should always create a variable before assigning it a value, and you’ll usually want to assign the variable a value before putting it to use. Trying to assign a value to a variable that does not exist, however, will cause VBScript to automatically create a new variable with the given name. This is called implicit declaration, because a new variable is declared implicitly as a result of your trying to assign a value to a variable that doesn’t exist. Since you are free to use implicit declaration for all of your variables, you may be wondering what the point is of using the Dim command to create each and every variable by hand.

The answer has to do with how easy you want it to be to find typing mistakes in your code. VBScript provides another command, Option Explicit, which causes ASP to disallow implicit declarations and instead display an error message whenever you try to assign a value to a non-existent variable. Why would you want this to happen? Consider the following example:

Dim intRoomTempC     ' Create a variable 
intRomTempC = 20     ' Assign the variable a value of 20

If you have a keen eye, you may have noticed that the variable name is misspelled on the second line. This is the kind of mistake that even experienced programmers make all the time. With implicit declaration enabled, the second line will create another new variable called intRomTempC and will store the value in that variable instead. Now, if the rest of your script expects that value to be stored in intRoomTempC, you’re going to run into trouble. In a large script, tracing such a problem back to one little typing mistake can be very time consuming. That’s where Option Explicit comes in:

Option Explicit      ' Disable implicit declaration 
Dim intRoomTempC     ' Create a variable
intRomTempC = 20     ' Assign the variable a value of 20

This time, ASP will report the typing mistake as an illegal implicit declaration, displaying an error message to that effect with the exact line number where the typing mistake was made. For this reason, I tend to explicitly declare all my variables with Dim and specify Option Explicit on the first line of all of my ASP scripts. It might take slightly longer to type, but it saves a lot of headaches when something goes wrong.

A shortcut exists for creating several variables at once on the same line. For instance, the following line would create two variables, intRoomTempC, and intFreezingC:

Dim intRoomTempC, intFreezingC  ' Two variables in one line

By now you may be wondering about my naming convention for variables. The two variables created in the above snippet both begin with int. I’m using this prefix to indicate that these variables will contain integers (whole numbers). You can feel free to name your variables whatever you like and store whatever kind of data you like in them, but I prefer to use this convention as a helpful reminder of the type of information in each variable. This practice of prefixing variable names with a clue as to their type is known as Hungarian notation, and I’ll introduce additional prefixes for other data types as they arise over the course of this series.

Using Variables

Once created and assigned a value, a variable may be used anywhere the value it contains might be used. Let’s look at a simple script that prints out the room temperature as stored in the variable intRoomTempC. Open your text editor and type the following (remember, don’t type the line numbers), then save the file as PrintRoomTemp.asp:

1  <% Option Explicit %>  
2  <!-- PrintRoomTemp.asp  
3       A simple script that prints out a variable. -->  
4  <html>  
5  <head>  
6  <title> Room Temperature </title>  
7  </head>  
8  <body>  
9  <p>Room temperature in degrees Celsius:  
10 <%  
11 Dim intRoomTempC             ' Declare a variable  
12 intRoomTempC = 20            ' Assign it a value  
13 Response.Write intRoomTempC  ' Write out the value  
14 %>  
15 </p>  
16 </body>  
17 </html>

This program is a lot like the very simple script we saw above, with a few notable exceptions:

  • Line 1: We specify Option Explicit at the top of this file to guard against typing mistakes in variable names, as described above. When used, this should always appear at the top of the file, before even any HTML tags; otherwise, it will produce an error message.
  • Lines 2-3: This is just an HTML comment tag. It doesn’t actually do anything, but I just thought I’d mention it in case you were not familiar with these.
  • Lines 11-12: As should be obvious to you by now, these two lines declare a variable called intRoomTempC and then assign it a value of 20.
  • Line 13: From the previous article, you should be used to seeing Response.Write used to print out some string of text (or see the example at the top of this article). In this case, however, the value following the command is not enclosed in quotes. As a result, instead of actually printing out "intRoomTempC", this line grabs the value stored in the intRoomTempC variable and prints that out.

Upload the file to your ASP-enabled Web host, or copy the file into the document root directory of the ASP-enabled Web server running on your computer, then open it in your browser by typing in the appropriate URL (e.g. http://www.myhost.com/~me/PrintRoomTemp.asp or http://localhost/PrintRoomTemp.asp). You should be presented with a Web page with the following text:

Room temperature in degrees Celsius: 20

Although the ASP code in this script effectively just prints out the number 20, the main purpose of this example was to demonstrate how to use a value stored in a variable. In this case, we printed the value out, but as you’ll see in later examples, variables can be used in many other ways as well.

An alternate method exists for printing out a value stored in a variable is to use the ASP. By surrounding a variable or some other ASP expression with the special <%= ... %> delimiters, the value of that variable or expression will be placed in the page at that location. Have another look at the example we just saw, but this time I’m using this nice shortcut:

1  <% Option Explicit %>  
2  <!-- PrintRoomTemp.asp  
3       A simple script that prints out a variable. -->  
4  <html>  
5  <head>  
6  <title> Room Temperature </title>  
7  </head>  
8  <body>  
9  <%  
10 Dim intRoomTempC             ' Declare a variable  
11 intRoomTempC = 20            ' Assign it a value  
12 %>  
13 <p>Room temperature in degrees Celsius: <%=intRoomTempC%></p>  
14 </body>  
15 </html>

Notice how the code for creating the variable and assigning it a value must come before the special tag that prints out the variable’s value. Although it may not look it, this special tag is still considered ASP code, and will be processed as such. So it makes sense that you should have to assign the variable its value before printing it out.

Operators

As I said above, any program that does anything useful will likely have to perform some kind of calculation, or manipulate information in some way or another. So far we’ve seen how to define pieces of information and store them in variables in preparation for that work to be done. In this section, I’ll introduce some of VBScript’s operators. Using operators you can take simple values (like numbers and strings of text) and perform operations on them (like addition, subtraction, or concatenation).

Let me show you a few simple examples so you know what I mean:

Dim intA, intB, intC ' Three integer variables   
intA = 10            ' Assigns value 10 to intA  
intB = 10 + 1        ' Assigns value 11 to intB (+ is addition)  
intC = intB – intA   ' Assigns value 1 to intC (- is subtraction)  
intA = intB * 3      ' Assigns value 33 to intA (* is multiplication)  
intC = intA / intB   ' Assigns value 3 to intC (/ is division)

Notice how I used the symbols +, -, *, and / to perform addition, subtraction, multiplication, and division respectively. These symbols are arithmetic operators. Notice also that operators may be used on literal values (10 + 1), variables (intB – intA), or both (intB * 3).

Other arithmetic operators that are less commonly used include the modulus operator (MOD) and the exponentiation operator (^):

intC = intB MOD 3    ' Assigns value 2 to intC (MOD is modulus op.)   
intB = intC ^ 2      ' Assigns value 4 to intB (^ is exp/power op.)

The modulus operator gives the remainder of an integer division. In the first example above, the value stored in intB (11) divided by three is 9 with a remainder of 2 – this remainder is the value calculated by the modulus operator. On the second line, the value stored in intA (33) divided by three is 11 with a remainder of 0, which is the value resulting from the modulus operation.

The exponentiation, or power operator is used to raise a number to some power. In this case, we’re raising the value stored in intC (2) to the second power. In other words, we are squaring 2 to obtain 4, and this is the value resulting from the exponentiation operator.

You can perform multiple operations in a single statement, if you want to. Note that arithmetic operations obey the same rules of precedence as they do on a scientific calculator: multiplication and division first, followed by addition and subtraction. Of course, we can use parentheses to change this if we want:

intA = 1 + 2 * 3     ' intA = 7   
intB = (1 + 2) * 3   ' intB = 9

Recall that variables don’t have to contain numbers. They can also hold strings of text; and operations can be performed on strings as well:

Dim strName   
strName = "Kevin"  
Response.Write "Hi " & strName & ", how are you today?"

The code above displays the message Hi Kevin, how are you today? Notice how the & operator is used to stick strings of text together (in other words, concatenate strings). For obvious reasons, & is called the string concatenation operator. Notice also that we’ve used the result of the expression "Hi " & strName & ", how are you today?" as the value to be printed out by the Response.Write command. Nothing says we must store the result of an arithmetic calculation or other operation in a variable; as the example above shows, if we only need the value in one place we can simply type the expression where we need it. Finally, note the new variable name prefix str, which I use to indicate a variable containing a string of text.

Another family of operators is called the comparison operators. As their name suggests, these operators are used to compare different values together. While the arithmetic operators produce numbers and the string concatenation operator produces text strings, the comparison operators produce Boolean values (i.e. either true or false). As before, some examples should illustrate this effectively:

' From above: intA = 7, intB = 9, and intC = 2   
 
Dim blnD, blnE, blnF    ' Three more variables  
blnD = (intA = 7)       ' blnD = True (= tests equality)  
blnE = (intA = intB)    ' blnE = False (intA doesn't equal intB)  
blnF = (intA <> intB)   ' blnF = True (<> tests inequality)  
blnD = (intA > 0)       ' blnD = True (intA is greater than 0)  
blnE = (intB < 6)       ' blnE = False (intB is not less than 6)  
blnF = (intC >= 2)      ' blnF = True (intC is greater/equal to 2)  
blnD = (intC <= 1)      ' blnD = False (intC isn't lesser/equal to 1)

As shown here, the comparison operators are =, <>, >, <, >=, and <=. Astute readers may have noticed that ‘=’ plays a dual role in VBScript, acting as either the assignment operator or the comparison for equality operator, depending on the context in which it is used. ‘=’ and ‘<>’ may also be used to check if two variables contain the same or different string values, respectively. I use the bln prefix for the variables’ names to indicate that they will contain Boolean values (True or False).

You might be wondering about the practical uses of these comparison operators. In fact, they are essential when it comes to making your program do different things under different conditions. To accomplish such a feat, however, you’ll need one more tool in your belt: control structures.

Control Structures

Don’t let the name scare you; control structures aren’t as complicated as they sound! All of the example scripts we’ve seen so far have had one thing in common: they’ve executed in a straight line, one ASP statement at a time, from top to bottom. In simple terms, control structures let you break out of that straight-line mould, allowing your programs to react differently to different conditions and saving you some typing when performing repetitive tasks.

Let’s start with the most basic control structure, an If...Then statement:

If condition Then statement

If the condition is true, then the statement will be executed. If not, nothing happens and the ASP engine just moves on to the next line of the script. Here’s a simple example:

' Check if intA and intB are equal    
Dim blnABEqual    
blnABEqual = (intA = intB)    
if blnABEqual Then Response.Write "A and B are equal!"

This is the practical application of the comparison operators that I promised above! The first line of the above (after the comment) creates a variable called blnABEqual. The next line checks if intA and intB are equal (that is, if they contain the same value). If they are, blnABEqual is assigned a value of true. If not, blnABEqual is set to false. If you printed this variable out, it would display either "True" or "False" on the page, depending on the values of intA and intB. On the last line, we have an If...Then statement that uses blnABEqual as its condition. As you can see, if intA and intB are equal (and thus blnABEqual is true), the program prints out a message to that effect. If not (and blnABEqual is false), then nothing happens.

Since most conditions are only used once, it is more common to type the conditional expression directly in the If...Then statement, instead of using a variable. Here’s how the above example would normally look:

' Check if intA and intB are equal    
If intA = intB Then Response.Write "A and B are equal!"

Pretty spiffy, eh? As always, use whichever method you are most comfortable with. Here are a few more examples of comparison operators in action as part of If...Then statements:

If intA > intB Then Response.Write "A is greater than B"    
If intA < intB Then Respone.Write "A is less than B"    
If intA >= intB Then Response.Write "A is greater or equal to B"    
If intA <= intB Then Response.Write "A is lesser or equal to B"    
If intA <> intB Then Response.Write "A does not equal B"

Instead of a single statement, you can specify a whole series of statements that should be executed if the condition is true. You do this by starting the list of statements on a new line and terminating the list with End If. Here’s an example:

If blnUserIsKevin Then    
 Response.Write "Hi, Kevin!"    
 Response.Write "How are you today?"    
 ' ... more statements here ...    
End If

Before I continue, a note on coding style. You probably noticed that some of the lines of the above example have spaces in front of them. This coding style, known as indenting is intended to show off the structure of the code. That is, by indenting the statements that will occur as a result of the condition being true by two spaces, it makes clear the fact that they are inside the If...Then statement. The code could have been written without indenting (with every line starting at the left margin), and it would have worked just as well, but the structure would not have been obvious at a glance. When you get to a stage where you’re writing complicated scripts, it will not be uncommon for certain passages of your code to be indented five or even ten levels deep (from If...Then statements inside If...Then statements, for example). By picking up this good habit now, you can ensure that your code is easy to read now and in future.

Getting back to If...Else statements, if you want to do something when a condition is false instead of when it is true, there is a handy shortcut you can use. Here’s how the code might look without using the shortcut:

' Print message when blnCondition is false    
If blnCondition = False Then    
 Response.Write "blnCondition is false!"    
End If

The = operator (and the <> operator) can be used on Boolean values as well as on numeric types and text strings. As a result, the condition in the If...Then statement above will be true when blnCondition is false, and false when blnCondition is true. The shortcut I mentioned involves something called the negation operator. By placing this operator (NOT) before a variable name or before some expression, the value of that variable or expression will be flipped from true to false (and vice versa). Thus, the above example could be more simply written as follows:

' Print message when blnCondition is false    
If NOT blnCondition Then    
 Response.Write "blnCondition is false!"    
End If

If blnCondition is true, the NOT operator will cause the condition to evaluate to false so the message will not be printed. If blnCondition is false, the NOT flips the expression’s value to true and the message does get printed. It’s important to note that the NOT operator doesn’t actually change the value that is stored in blnCondition; it just alters the value of the condition for the purposes of the If...Then statement.

Another control structure that is related to the If...Then statement is the If...Else statement:

If condition Then    
 ' statements to be executed if condition is true    
Else    
 ' statements to be executed if condition is false    
End If

In this case, one group of statements or the other will be executed. The condition determines which. Often, however, you’ll have more than just two groups of statements that you’ll want to choose from. By using another If...Else statement in as the second indented block of statements, you can test multiple conditions and perform an action depending on which of the conditions is true:

If condition1 Then     
 ' do this if condition1 is true    
Else    
 If condition2 Then    
   ' do this if condition2 is true    
 Else    
   If condition3 Then    
     ' do this if condition3 is true    
   Else    
     ' do this only if none of the conditions is true    
   End If    
 End If    
End If

Confused? If you wade through the above, you should eventually be able to piece together the three If...Else statements that involved, but you’ll probably be happy to know that there is an easier way. Using ElseIf to specify your additional conditions, you can do away with the nested If...Else statements. Here’s the previous example reworked using ElseIf:

If condition1 Then     
 ' do this if condition1 is true    
ElseIf condition2 Then    
 ' do this if condition2 is true    
ElseIf condition3 Then    
 ' do this if condition3 is true    
Else    
 ' do this only if none of the conditions is true    
End If

Loops

The rest of the control structures that I’ll discuss in this article have to do with making your script perform the same operation several times without having to type the commands for that operation over and over again. These structures are normally called loops.

The first type of loop is called a Do-While loop. Its name suits its function: to do something over and over again while a condition remains true. Here’s what a Do-While loop looks like:

Do While condition     
 ' a block of commands (the loop body)    
Loop

The operation of a Do-While loop is best illustrated by the flowchart in Figure 1.

Figure 1: A standard Do-While loop

In most cases, the condition for a Do-While loop will be something that starts off being true, but eventually will change to false after the block of commands has been executed a certain number of times. Here’s a simple script that uses a Do-While loop:

1  <% Option Explicit %>     
2  <!-- Countdown.asp    
3       A simple ASP script that counts down from 10. -->    
4  <html>    
5  <head>    
6  <title> Countdown to Liftoff </title>    
7  </head>    
8  <body>    
10 <%    
11 Dim intCount    
12 intCount = 10    
13    
14 Response.Write "<p>Countdown to liftoff... T Minus "    
15    
16 Do While intCount > 0    
17   Response.Write intCount & "!<br>"    
18   intCount = intCount - 1    
19 Loop    
20    
21 Response.Write "Liftoff! We have liftoff!</p>"    
22 %>    
23 </body>    
24 </html>

Here’s what’s new in this program:

  • Lines 11-12: We declare a variable called intCount with an initial value of 10.
  • Line 16: A Do-While loop that will continue for as long as intCount is greater than 0.
  • Line 18: Subtract 1 from the value stored in intCount

So when the program first gets to the Do-While loop, intCount is 10 so the loop body is executed, printing out "10!" and then subtracting 1 from the value stored in intCount. The condition is then checked again. 9 is still greater than zero, so the loop body is executed once more ("9!"). This continues until the 10th time the loop body is executed ("1!"), when subtracting 1 from intCount brings its value to zero. Now when the condition is checked it is false; thus, the loop stops and execution continues following the loop.

Here’s what you should see when you view the results of the script in your browser:

Countdown to liftoff... T Minus 10!     
9!    
8!    
7!    
6!    
5!    
4!    
3!    
2!    
1!    
Liftoff! We have liftoff!
Do-While loops are very handy, but there are two limiting cases you should be aware of:

  • If the condition is false to begin with, the loop body won't be executed at all.
  • If the condition stays true forever, the script will execute the loop over and over and will eventually time out, causing an error message to be displayed.

While the first case has its uses, the second case is something to be careful of. A loop that never ends is called an infinite loop. Infinite loops can happen under the most unexpected circumstances, and are a surprisingly common mistake that even experienced programmers sometimes make. If one of your scripts ever seems to get 'stuck' and just leaves your browser hanging, chances are good that it's gotten stuck in an infinite loop. If you wait long enough, eventually the script will run into the script time limit on your server and an error message explaining that the script exceeded the maximum allowable execution time. To see what this would look like, just change the condition for the Do-While loop on line 16:

16 Do While True

Don't worry; it won't hurt your computer. It might slow things down a bit until the script times out, though.

For Loops

The final control structure we'll be seeing in this article is similar to a Do-While loop, and is called a For loop. The For loop provides a nice shortcut for the most common application of Do-While loops. Here's what the syntax looks like:

For counter = start To end [Step step]      
 ' loop body      
Next

In the above, counter is the name of a variable that will store a value that will count either up or down each time through the loop, start is the value that the counter variable should start at the first time through the loop, and end is the value that the counter variable should have the last time through the loop. The optional step parameter is the amount by which the counter variable should change after each time through the loop. If it is not specified, the value will simply be increased by one each time through the loop. The operation of a For loop is illustrated in Figure 2.

Figure 2: A For loop

To demonstrate a For loop in practice, I've adapted the countdown script above to use a For loop instead of a Do-While loop. Note that in this case we want the counter variable to count down from 10 to 1, so we specify a step value of –1.

1  <% Option Explicit %>      
2  <!-- Countdown.asp      
3       A simple ASP script that counts down from 10. -->      
4  <html>      
5  <head>      
6  <title> Countdown to Liftoff </title>      
7  </head>      
8  <body>      
9  <%      
10 Dim intCount      
11      
12 Response.Write "<p>Countdown to liftoff... T Minus "      
13      
14 For intCount = 10 To 1 Step -1      
15   Response.Write intCount & "!<br>"      
16 Next      
17      
18 Response.Write "Liftoff! We have liftoff!</p>"      
19 %>      
20 </body>      
21 </html>

The code in this script is fairly similar to the original version with the Do-While loop; we've just cut a few corners! The creation of the intCount variable stayed the same (line 10), but we no longer need to give it an initial value, because the For loop takes care of that. The command from the loop body that subtracted 1 from the value of the intCount variable is no longer necessary either. So, what a For loop lets you do is combine all of the commands having to do with the initialization, checking, and updating of a counter variable (intCount, in this case) into a single line, making the code in general easier to read.

Even though any For loop could be expanded out into a Do-While loop with the appropriate statements before the loop and at the end of the loop body, it is common practice (and generally tidier) to express any loop that uses a counter variable as a For loop.

Summary and Further Reading

Learning the basic syntax of a programming language is rarely very riveting stuff, so unfortunately such material doesn't make for the most exciting of articles. Nevertheless, in this article you have been exposed to the most important features of the VBScript programming language commonly used for writing dynamic Web sites in ASP. We looked at how variables let you store data for use in calculations, what operators are available for putting pieces of data together and getting a result, and what control structures let you make programs that do something other than go in a straight line.

A few of the less basic features of the language (such as the select-case control structure and logical operators) were left out due to space constraints, but these will be covered where appropriate in later instalments of the series. In the meantime, if you're looking for a complete guide to the VBScript language, check out the Microsoft Scripting Technologies Web site.

With the mundane details of VBScript out of the way, you should now be ready to make the leap into the world of building dynamic Web sites with ASP. And that's exactly what I'll be covering in next month's article! See you back here in 30!

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • http://notfound mohamed kamal

    I want to learn the language of the ASP