Active Server Pages/Expressions

From Wikibooks, open books for an open world
Jump to: navigation, search
Previous: Variable Types Index Next: Conditionals and Looping

Objectives[edit]

In this section, you will learn how to build expressions in Active Server Pages. After studying this section, you will learn how to build an expression and learn how to combine varibles and string literals in combination to manipulate data.

Content[edit]

An expression is a group of literal and variables which are organized in a structured format using operators. The best example of an expression is a mathematical expression such as x + 3.

Expressions are made up of a collection of mathematical, comparison, bit-wise and logical operators as well as literal values and ASP variables which are placed together for evaluation by the ASP Interpreter. Once an expression is evaluated, it can be assigned to a variable, used as the argument to an ASP procedure or output on an ASP page.

Assignment[edit]

One of the most basic statements you can make in ASP is an assignment. This basically evaluates an expression and places the result into a variable. The equals sign (=) separates the variable that gets the result (on the left side) and the expression to build the result (on the right side).

 <%
 Dim nX, dX, sName, bIsAdmin
 
 ' assign literal values
 nX = 13
 dX = 7645.34
 sName = "Barney Google"
 bIsAdmin = True
 
 ' or you can assign complex expressions like
 Dim dDateTime
 
 dDateTime = Now()
 nX = 13 + 23 - 10
 dx = (5 * nX) / 2.0
 sName = "Barney is " & CStr(nX)
 %>

Don't worry too much about some of the more complicated expressions found in this example. All of this will be explained later in this chapter. You should note that the left side of the expression is always a variable. You are only allowed to put a single ASP variable on the left side of the equals sign.

Evaluation Order[edit]

The way an expression is evaluated, depends on the operator precedence. Precedence is kind of an importance assigned to an operator. Operators that have the highest precedence are evaluated first and those that have the lowest are evaluated last. When two operators exist that have the same precedence, the operators are evaluated from left-to-right.

Take for example the following expression:

dX = 6 - 3 * 4 + 2

In this example, you will see we have three different operators. The "+" and the "-" operator have the same precedence while the multiplication operator (*) has a higher precedence. In this case, the multiplication takes place first reducing the expression to:

dX = 6 - 12 + 2

Now there are two expressions that have the same precedence. In this case, we evaluate the left-most expression first. After two more reductions we get the final result:

 dX = -6 + 2
 dx = -4

You should note also that if we had evaluated the expression from the other direction we would get a completely different result. This order of evaluation follows the same method used in mathematics (if you remember your basic algebra.)

Grouping Sub-Expressions[edit]

If you want to over-ride the default order-of-evaluation (precedence) for evaluating an expression, you can group expressions that should be evaluated first in parentheses. You can think of it as an expression embedded in another expression or a "sub-expression".

If you remember the example from the previous section, we can modify it to change the order-of-evaluation like so:

dX = (6 - 3) * 4 + 2

And just like in Algebra, we know that we have to evaluate these sub-expressions first. So the first step in reducing this type of expression is to evaulate the sub-expression:

dX = 3 * 4 + 2

The final reduction will yield a result of 14 which is a completely different result than we got before. Be careful about how you group your expressions. It can cause a lot of problems and increase the complexity of your code. If you want to keep your code simpler, you can always create new variables to store the results of sub-expressions.

 ' Using variables to evaluate sub-expressions
 Dim dX, dY
 dY = 6 - 3
 dX = dY * 4 + 2

Mathematical Expressions[edit]

The following table lists all of the binary mathematical operators. They are "binary" because they require two arguments. The first argument is on the left-side and the second argument is on the right-side. So the operator "+" in the expression "5 + 6" has the binary arguments "5" and "6".

Symbol Operator Example
+ Addition nX + 5
- Subtraction nX - 5
* Multiplication dX * 1.5
/ Division dX / -1.5
\ Integer Division dX \ 6
% Modulus (remainder) nX % 6

The following table lists all of the unary mathematical operators. A unary operator only has a single argument to act on.

Symbol Operator Example
- Negation -nX

Of course you can combine binary and unary operators in one expression. The results of one binary operation might serve as the argument to your unary operation.

 ' combining the binary "+" with the unary "-"
 dX = -(nX + nY)

There are many advanced mathematical functions that can be used to do complex arithmetic which we will talk about later. These will not be covered in this chapter.

String Operators[edit]

When working with strings, Active Server Pages provides a wealth of functions for manipulating strings. But since we are only talking about operators that may be used in an expression, we will only be dealing with the one string operator here: the string concatenation operator.

String concatenation means that you want to append one string to another. This operation is a binary operation meaning that it takes two arguments: the left-side is the string you want to append to and the right-side is the string that you want to append.

 Dim sFirst, sLast, sFullName
 sFirst = "Bill"
 sLast = "Gates"
 sFullName = sFirst & " " & sLast

As you can see in the example above, we are using the string concatenation operator to append three string values together: "Bill", " ", and "Gates". Two of the strings are stored in variables while the space character is just a string literal.

You may concatenate as many variables as you want together using the string concatenation operator. It has been shown that string concatenation under Active Server Pages is very inefficient. So if your page is performing slowly and you have a lot of string concatenations, you should look for ways to eliminate them.

Comparison Operators[edit]

Comparison operators, as you might have guessed, are used to compare two different expressions and return a value of "true" or "false". In most cases the two expressions being comparted will evaluate to a number, but it is possible to compare string values, dates and booleans.

The following table lists the binary comparison operators. These operators require two expression arguments: one on the left-side of the operator and one on the right-side. Just like mathematical expressions, you may combine two-or-more of these expressions together. In the next section we will explain how to these are combined using logical operators.

Symbol Operator Example
= Equality nX = 5
<> Inequality (Not Equal) nX <> nY
< Less Than nX < 5
> Greater Than nX > -5
<= Less Than or Equal nX <= 5 + nY
>= Greater Than or Equal nX >= dY * 5.0 - 2

These operators are most commonly used in an If Then statement which will take an action based on the boolean result of an expression. Unless you already have a boolean value stored in an ASP variable, you will need to write an expression like the following:

 If nX >= 60 Then Response.Write "You Passed!"
 If nX < 60 Then Response.Write "You Failed"

Of course, your expression can be as complicated as you want as long as it evaluates to a boolean value.

Logical Operators[edit]

Whereas mathematical expressions are used to manipulate numbers, logical operators are used to work with the two boolean values "true" and "false". These operators are always used to combine two expressions that result in boolean values.

Symbol Meaning Example
And True only if both arguments are true, otherwise false nX > 5 And nX < 10
Or True if either argument is true, false only when both arguments are false nX < 5 Or nX > 10

In addition to these binary operators, there is also one unary operator:

Symbol Meaning Example
Not Negation, true becomes false and false becomes true Not (nX > 5)

The negation operator basically will give you the opposite value of the expression. So if the expression evaluates to "true" and you perform the Not operation on it, it becomes "false". Conversely, "false" will become "true" when Not is applied.

So using these logical operators, we can group many comparison expressions together to create a very complex expression like so:

 ' example of a complex expression with four comparisons)
 If (nX = 2) Or (nX < 10 And nX < 20) And Not (nY * 5.0 - 2 <= 17.0) Then
     Response.Write "Yes"
 End If

The first comparison (nX = 2) looks just like an assignment. You can never put an assignment in an expression like this. Assignment only occurs at the start of an expression, where the first symbol is an ASP variable which is followed by the assignement (=) operator.

You will notice that we used parentheses to group the expressions. Even in some cases where parentheses are not required, it sometimes makes your expressions easier to read when you put them in there.

Bit-Wise Operators[edit]

For advanced programming, Active Server Pages has operators for working with individual "bits". A "bit" is the digit used in the binary number system and was formed from a contraction of the words "binary digit". It can only have one of two different values: "0" and "1".

In the old days of computer, programmers were severely limited in storage and had to make the most of the available storage. One way they did this was by combining multiple variables into a single "byte". This has carried through to modern-day computer systems and this is why we need bit-wise operators.

In computer terms, we talk about "bytes". A byte is composed of 8 "bits" and therefore can have 2 ^ (raised-to-the-power) 8 or 256 possible values. An integer is composed of two bytes so it can have a value of 256 ^ 2 or 65536 possible values.

 The 8 bits from a byte and their integer equivalents

 +-------------------------------------------------------+
 | Bit7 | Bit6 | Bit5 | Bit4 | Bit3 | Bit2 | Bit1 | Bit0 |
 +------+------+------+------+------+------+------+------+
 |  128 |   64 |   32 |   16 |    8 |    4 |    2 |    1 |
 +-------------------------------------------------------+

For all of the bits that are set (equal to 1) above, you need to add their integer equivalent to determine the resulting byte value. So If bits 6, 4, 1 and 0 were set, the equivalent byte value would be: 64 + 16 + 2 + 1 = 83.

Going the other way around, we can convert an integer to binary. We just take the integer value and subtract the biggest binary value we can and note the corresponding bit. We continue to do this subtracting binary values until we come up with the resulting bit string:

 ' convert integer value (221) to binary
 221 - 128 = 93 (binary 0x10000000)
 93 - 64 = 29 (binary 0x11000000)
 29 - 16 = 13 (binary 0x11010000)
 13 - 8 = 5 (binary 0x11011000)
 5 - 4 = 1 (binary 0x11011100)
 1 - 1 = 0 (binary 0x11011101)

When working with the bit-wise operators, we sometimes have to convert between binary and integer like this and vice-versa.

In Active Server Pages, bit-wise operators are only used on numeric expressions to manipulate individual bits. The numberic expression can evaluate to integers, longs, single or double-precision numbers. After evaluating the bit-wise operation, the resulting value will be compatible with the original arguments.

The following bit-wise operators require two arguments: one on the left-side of the operator and one on the right-side.

Symbol Meaning Example
& Bit-wise And nX & 5
| Bit-wise Or nX | 48
^ Bit-wise Exclusive Or nX ^ 48
<< Shift Bits Left nX << 2
>> Shift Bits Right nX >> 1

The following operators are "unary" operators meaning they only require one argument. The single expression argument must be to the right-side of this operator.

Symbol Meaning Example
~ Bit-wise Negation ~ nX

Truth Tables[edit]

Truth tables display the results of the binary operators on a bit-by-bit basis. You can think of each bit in the arguments being evaluated one-by-one. Bits are matched up based on their position in the bytes. So for a 16-bit integer, each bit would be operated on individually and the resulting bits would be strung together in the same order to generate the resulting number.

When viewing these tables, think to yourself "When performing a bit-wise and (&), bit 0 from argument 1 and bit 0 from argument 2 are anded together and the result is X. Next bit 1 from argument 1 and bit 1 from argument 2 are anded together and the result is Y". And continuing on for all the bits in the arguments.

And (&) Operator Truth Table
Arg #1 Arg #2 Result
0 0 0
0 1 0
1 0 0
1 1 1


Or (|) Operator Truth Table
Arg #1 Arg #2 Result
0 0 0
0 1 1
1 0 1
1 1 1


Exclusive Or (^) Operator Truth Table
Arg #1 Arg #2 Result
0 0 0
0 1 1
1 0 1
1 1 0


Negation (~) Operator Truth Table
Arg #1 Result
1 0
0 1

Manipulating Date and Time Values[edit]

ASP has some built-in functions to manipulate datetime values. Thought technically not operators, we mention them here for completeness since datetime is a valid data type and it is often necessary to calculate dates and times.

Date and Time Functions
Function Purpose
Date Get the current date according to the local machine
dNow = Date()
Time() Get the current time as a datetime value according to the local machine
dTime = Time()
Now() Get the current date AND time according to the local machine
dNow = Now()
DateAdd(Interval, Number, Date Add a specific Number of Interval to the supplied date
DateAdd("d", 3, Now())
DateDiff(Interval, Date1, Date2) Calculate the number of Interval difference between Date1 and Date2
dDaysLeft = DateDiff("d", Now(), dBirthDay)
DatePart(Interval, Number, Date) Retrieve a specific part of a date such as the hour or month
DatePart("yyyy", Now())
DateSerial(Year, Month, Day) Construct a datetime value from the year, month and day components
dBirthday = DateSerial(1998, 12, 23)
TimeSerial(Hour, Minute, Second) Construct a datetime value reflecting the time components.
dNapTime = TimeSerial(14, 0, 0)
DateValue(DateTime) Convert a date string into a datetime value.
DateValue("12/23/1998")
TimeValue() Convert a time string into a valid datetime object.
dTime = TimeValue("10:51:43 PM)
Day(Date) Retrieve the day-of-the-month (0-31) for a specific datetime value
Day(Now())
Month(Date) Retrieve the month (1-12) for a specific datetime value
nMonth = Month(dBirthDay)
Year(Date) Retrieve the year for a specific datetime value.
Year(Now())
Hour(Datetime) Retrieve the hour (in 24-hour military time format [0-23]) for the datetime value
Hour(Now())
Minute(Datetime) Retrieve the minute (0-59) component for a specific datetime value
nMinute = Minute(dBirthDay)
Second(Datetime) Retrieve the seconds (0-59) for a specific datetime value.
Second(Now())
FormatDateTime(Datetime) Format the specified datetime value in a standardized format
FormatDateTime(Now(), vbLongDate)

Information about optional arguments for these functions and valid interval types will be discussed in a later chapter. You should note that none of the mathematical operators apply to datetime values. You must use the various conversion and calculation functions above to manipulate dates.

Line Continuation Operator[edit]

If you have a really long line in ASP that you would like to split into two lines, you can use the line continuation operator. This is an underscore (_) placed at the end of the line that tells the ASP interpreter that statement or expression continues on the next line.

 if ((bDaysLeft < DateDiff("d", Now(), dBirthDay)) Or _
   (bDaysLeft > DateDiff("d", Now(), dChristMas)) Then
        Response.Write "Hooray!"
 End If

In the example above, we use the line continuation to continue a boolean expression. You may use it to continue any type of expression or statement. It makes sense to split up long lines for readability. Just be careful how you split lines so that you don't make the line more confusing to read.

Summary[edit]

There are eight different types of operators in ASP:

  • Assignment Operators
  • Mathematical Operators
  • String Operators
  • Comparison Operators
  • Logical Operators
  • Bit-wise Operators
  • Grouping Operators
  • Line Continuation Operator

All but the assignement operators can be used for building expressions. Operators are evaluated based on precedence and the grouping operators. If two operators have the same precedence, then the operators are evaluated from left-to-right.

All date and time values must be manipulated using functions. The mathematical operators are invalid on datetime values.

Review Questions[edit]

  • What must be on the left-side of the assignment operator?
  • What must be on the right-side of the assignment operator?
  • What are the eight major types of operators?
  • What is meant by operator precedence?
  • Which operator is used to group expressions?
  • How are datetime values used in expressions?

Exercises[edit]

  • Write the conditional expression to test a variable (nSpeed) is less than or equal to the speed limit (nSpeedLimit)
  • Write an expression to convert a temperature in Fahrenheit to degrees and vice-versa
  • Create a function that calculates the number of days from now until Christmas.
  • Create a page that inputs a user's birthday and then calculates how old that person is.
Previous: Variable Types Index Next: Conditionals and Looping