Teach Yourself VBScript in 21 Days
DAY 5
Putting Operators to Work in VBScript
CONTENTS
- Working with Operators
- Arithmetic Operators
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/ and \)
- Exponents (^)
- Modulo Arithmetic (Mod)
- Negation (-)
- Comparison Operators
- Equality (=)
- Inequality (<>)
- Less Than and Greater Than (< and >)
- Less Than or Equal To and Greater Than or Equal To (<= and >=)
- Object Equivalence (Is)
- Logical Operators
- Negation (Not)
- Conjunction (And)
- Disjunction (Or)
- Exclusion (Xor)
- Logical Equivalence (Eqv) and Implication (Imp)
- Working with Strings
- Operator Precedence
- Summary
- Q&A
- Workshop
- Quiz
On Day 4, "Creating Variables in VBScript,"
you learned how to create and use variables. It is important for
you to master this skill because variables are fundamental in
almost all aspects of VBScript programming. Now that you've seen
how to create variables, you need to know how to use operators
to make those variables do useful work for you. Operators
are given that name because they operate on the variables
associated with them. For example, the addition operator (+)
is one of the operators you can use in VBScript. The addition
operator is applied to operate on one or more variables-in this
case, to add the variables together.
An operator is a symbol applied to data values (such as variables) that causes the computer to carry out a specific operation on that data (for example, multiplication, subtraction).
Today you will learn each of the VBScript operators and see some examples of how to use them. If you've used Visual Basic or some other programming language in the past, much of what's contained in today's lesson will be a review for you. Still, you need to know how VBScript differs from the languages you've used before, so in either case, this lesson is important to you. After introducing the principals of fundamental operators, I also discuss string operators-particularly the rules about how to append strings together.
Today's lesson, together with yesterday's coverage of variables and the rest of the lessons in this first week, will give you a solid foundation for getting started with VBScript.
Working with Operators
As you begin to write VBScript code, you will use operators so much that their use will become natural to you. In this section, you will learn about each of the operators available to you in VBScript, as well as how you might go about using them.
Arithmetic Operators
The first major class of operators is arithmetic operators. Arithmetic operators enable you to perform simple arithmetic on one or more variables. Most of these operators will be familiar to you because you have been exposed to them in everyday life. Few people will be surprised to find, for example, that the + operator performs addition! Some operators, however, might be new to you. In any case, you need to understand how to apply these operators to variables and literals in VBScript code, and today's lesson will teach you how.
Arithmetic operators are a class of operators specifically
intended to perform arithmetic on the corresponding data.
Note |
Just a reminder: The term literal means "take the data literally." For example, the following message box statement prints the contents of variable VarA: msgbox "My favorite number is " & VarA The next message box prints the literal 100. This means it will directly reference the number 100 without using a variable: msgbox "My favorite number is " & 100 The second message box used the literal data representation, which was directly coded into the statement, rather than a variable. Such data is called literal data. Operators can essentially work on any type of data, whether it is literal data or the intrinsic constants and variables introduced yesterday. Because most of the time you'll use variables with the operators, I use the term variables for the sake of simplicity when I refer to what operators work on. (The more formal computer science term for what operators work on is operands.) |
Addition (+)
The first arithmetic operator is the addition operator. You already used this operator yesterday and probably intuitively understood its purpose because it is so commonly used and easy to understand. The addition operator is used to add values, whether they are stored in variables, constants, or literal numbers. You also use the + operator to concatenate strings, but for now, just focus on its ability to add numbers-I'll discuss string concatenation later today.
You can add variables, numbers, and constants in a variety of combinations with the addition operator. For example, you can use the addition operator to add two numbers together and assign them to a variable:
Orders = 2 + 3
You can also add a number to a variable and assign it to another variable:
Result = Quantity + 15
You can even add a constant to a variable and store the result in another:
BoxType = vbYesNo + vbQuestion
You can add as many numbers, variables, and constants as you want:
Guests = Mine + 5 + His + 8 + Hers
In life, people are always adding things together. You add the tip to your meal cost over lunch; you add up your W2 forms at tax time. You add the number of bills you have to pay this month. You add numbers all the time. Likewise, when you're writing code, you use addition all the time. The addition operator can be used for a variety of purposes.
Consider the simple example in Listing 5.1. In this case, the user wants some way-out, radical t-shirts from your Way-Out, Radical T-Shirt Shop. The user must enter into the Web page the total number of shirts he or she wants of each color you offer. You can calculate the total number of shirts the user wants by simply adding the number of each color. That way, the program can determine how many shirts the user wants so that the script can put together a cost.
Listing 5.1. Using the addition operator to calculate the number of shirts to order.
<HTML>
<TITLE>The Way-Out, Radical T-Shirt Shop</TITLE>
<H1><A HREF="http://www.mcp.com"><IMG ALIGN=BOTTOM
SRC="../shared/jpg/samsnet.jpg" BORDER=2></A>
T-Shirt Order Form</H1>
<BODY>
<HR>
<CENTER>
<PRE> Red Shirts <INPUT NAME="txtRed" SIZE=5></PRE>
<PRE> Green Shirts <INPUT NAME="txtGreen" SIZE=5></PRE>
<PRE> Blue Shirts <INPUT NAME="txtBlue" SIZE=5></PRE></CENTER>
<CENTER><INPUT TYPE=BUTTON VALUE="Order!" NAME="cmdOrder"></CENTER>
<HR>
<center>
from <em>Teach Yourself VBScript in 21 Days</em> by <A HREF="_
../shared/info/keith.htm">Keith Brophy</A> and
<A HREF="../shared/info/tim.htm">Tim Koets</A><br>
Return to <a href="..\default.htm">Content Overview</A><br>
Copyright 1996 by SamsNet<br>
</center>
<SCRIPT LANGUAGE="VBScript">
<!-- Option Explicit
Sub cmdOrder_OnClick()
Dim Quantity_Ordered
Dim Red
Dim Green
Dim Blue
Red = CInt(txtRed.Value)
Green = CInt(txtGreen.Value)
Blue = CInt(txtBlue.Value)
Quantity_Ordered = Red + Green + Blue
MsgBox "You have submitted a request to order " & _
Quantity_Ordered & " shirts!"
End Sub
-->
</SCRIPT>
</BODY>
</HTML>
This example offers three colors to the user. Figure 5.1 shows the Web page, named tshirt.htm on the CD-ROM that accompanies this book.
Figure 5.1 : Web page for ordering t-shirts.
As you can see from the figure, the Web page has three text boxes into which the user can enter how many shirts he or she wants to order. Then, the user simply clicks the Order! button to place the order. In this case, as shown in Figure 5.1, a message box appears, indicating the number of shirts the user has ordered.
Listing 5.1 shows the entire HTML document so you can see how the text box controls and button are placed on the Web page. Don't worry about the details of how this is done because these controls, along with many others, will be discussed on Day 8, "Intrinsic HTML Form Controls." In the procedure cmdOrder_OnClick, the number of shirts in red, green, and blue are taken from the text boxes where the user entered those numbers. The CInt function converts each of those values into integers rather than strings. After that, they are added together using
Quantity = Red + Green + Blue
and stored in the variable Quantity_Ordered. Finally, a message box tells the user how many shirts he has ordered.
This example shows you one way to use the addition operator. You will see many more examples of its use throughout this book.
Subtraction (-)
The subtraction operator should also be very familiar to you. This operator works the same way the addition operator does except that it subtracts one or more numbers rather than add them. Otherwise, the syntax is the same. You can subtract two numbers and assign the result to a variable:
Result = 100 - 37
You can also use variables:
Result = 100 - Count
You can also subtract more than two values:
Result = 100 - Count - Extras
You can combine addition and subtraction in the same code statement:
Result = May + June - July
To see how you might use the subtraction operator, consider the example in Listing 5.2. It's the same Web page shown in Listing 5.1, but you're adding more capabilities to it as you go. Suppose that you're running a special this month where the customer automatically gets one shirt free, regardless of how many he orders. A pretty generous offer, but hey-you're a generous person! The Web page is named discount.htm on the CD-ROM that comes with the book.
Listing 5.2. Using the subtraction operator to calculate the number of shirts the user will have to pay for.
Sub cmdOrder_OnClick()
Dim Quantity_Ordered
Dim Quantity_Charged
Dim Red
Dim Green
Dim Blue
Red = CInt(txtRed.Value)
Green = CInt(txtGreen.Value)
Blue = CInt(txtBlue.Value)
Quantity_Ordered = Red + Green + Blue
Quantity_Charged = Quantity_Ordered - 1
MsgBox "You have submitted a request to order " & _
Quantity_Ordered & " shirts!"
MsgBox "You will be charged for " & Quantity_Charged &
" shirts, because you get one shirt for free! "
End Sub
This code segment creates another variable called Quantity_Charged because the quantity charged will be one shirt less than the quantity ordered. You calculate the quantity charged by subtracting one shirt off the quantity ordered. The code in Listing 5.2 performs that subtraction and tells the user how many shirts he or she will actually be charged for. Figure 5.2 shows the message box that tells the user how many shirts he or she must ultimately pay for.
Figure 5.2 : Web page for ordering t-shirts at a discount.
Note |
You might have noticed that Listing 5.2 uses two separate message boxes to provide feedback to the user. Other, more elegant ways to provide user feedback will be covered in subsequent lessons. For now, using a message box in our examples for each piece of feedback to the user helps keeps things simple! |
Multiplication (*)
Addition and subtraction are important, but you also need to be able to multiply values together. In most computer languages, the * symbol is used to indicate multiplication, not the x symbol. You might be able to use x on paper, but to the computer, x is a variable, not a multiplication symbol. If you enter the command
Result = 3 x 2
the interpreter will give you a syntax error. Rather, you should enter the command
Result = 3 * 2
to be correct. Consider the shirt business example. You have the total number of shirts the customer has ordered as well as the total number of shirts the customer is going to be charged for. Now, figure out the cost. You're charging a meager sum of $20 per shirt. In order to determine the cost, multiply the number of shirts the customer has to pay for by the cost per shirt. Listing 5.3, taken from the Web page cost.htm on the CD-ROM, performs that multiplication.
Listing 5.3. Using the multiplication operator to calculate the cost of the shirt order.
Sub cmdOrder_OnClick()
Dim Quantity_Ordered
Dim Quantity_Charged
Dim Cost
Dim Tax
Dim Red
Dim Green
Dim Blue
Red = CInt(txtRed.Value)
Green = CInt(txtGreen.Value)
Blue = CInt(txtBlue.Value)
Quantity_Ordered = Red + Green + Blue
Quantity_Charged = Quantity_Ordered - 1
Cost = Quantity_Charged * 20
Tax = Cost * 0.06
Cost = Cost + Tax
MsgBox "You have submitted a request to order " & _
Quantity_Ordered & " shirts!"
MsgBox "You will be charged for " & Quantity_Charged & _
" shirts, because you get one shirt for free! "
MsgBox "The cost for the shirts is $" & Cost & "."
End Sub
As for our customer, he or she now has the cost of the shirt, as shown in Figure 5.3.
Figure 5.3 : Web page for ordering t-shirts with an added cost calculation.
A six percent sales tax is also added to the cost to make the local tax-collecting municipality happy. Now, you can present the customer with the total cost for the shirt. As you can see, not only is the multiplication operator useful, but it is often necessary to calculate useful information. You will see it used throughout the rest of the book.
Division (/ and \)
The division operator is the last of the four commonly used arithmetic operators. Among the common arithmetic operators, division is the most complicated arithmetic operation a computer performs. This shouldn't surprise you if you remember learning long division in grade school math class. VBScript has two types of division operators. The first operator handles numbers with decimal points. Usually referred to as the floating-point division operator, it's represented by the / symbol in code listings. If you are relatively new to programming, you might be wondering at this point if you can use a more familiar symbol for the same purpose. The answer is no; you cannot use the familiar Þ symbol in computer speak-you must instead use the / symbol for floating-point division. The floating-point division operator is designed to divide values with decimal points, but it can also divide numbers without decimals. The syntax for division is the same as any of the other operators presented so far:
c = a / b
This code divides the variable b into a and puts the result into the variable c. Similarly, you could use numbers and perform a division such as
c = a / 2
which, in this case, divides the variable a in half. If the variable a were set to some valid numeric value, say 3, the result stored in c would be 1.5.
From time to time, you might want to divide integer values or perform a division without a decimal point in the result. Suppose, for example, that it's bonus time at the Way-Out, Radical T-Shirt Company, and you'd like to divide the profits to distribute equally among all your employees. Suppose your bonus money amounts to $1,204 and you have 16 employees. If you divide the bonus money by the number of employees you have, you get the result
1204 / 16 = 75.25
Rather than hand out a bunch of quarters, you would like to give them paper money without the change. If you were to drop the decimal point off 75.25, you could just give everybody an even 75 dollars. This is one case where integer division comes in handy.
The integer division operator essentially tells VBScript to return a non-decimal result. When considered in terms of the variant subtypes discussed on Day 4, the result will be either a long or integer subtype, depending on how large the resulting number is. In either case, the answer returned from the division will have no decimal representation. Although VBScript accomplishes this by treating each part of the division as an integer, you can picture the result as the normal floating-point result with any decimal points in the number rounded off. A calculation that would yield 14.75 with floating-point division becomes 15 with integer division. Similarly, a floating-point division that produces 14.25 would provide a result of 14 with integer division.
Note |
You can also apply your own rounding techniques to any floating-point number. These are covered on Day 16, "Extending Your Web Pages with Dates and Advanced Math." |
Integer division is performed the same way floating-point division is, but the operator is different. Rather than use a forward slash (/), you use a backward slash (\). The following code shows the syntax:
Result = a \ b
Returning to the t-shirt example, if you coded the bonus calculation in your script as
c = 1204 / 16
you would end up with the value of 75.25 stored in variable c. On the other hand, if you coded the calculation as
c = 1204 \ 16
you would be left with the desired result of 75 in variable c because integer division would have occurred.
It is important to realize that integer division turns your result into an integer by rounding the original values of the operands to integers to calculate the results. For example, consider the result of the following calculation:
c = 4 \ 1.9
The value of variable c after this statement executes will be 2. VBScript processes this calculation after an internal rounding of the operands. The expression VBScript will act upon in this case is not c = 4 \ 1.9 or c = 4 \ 1. Rather, it rounds the operands to perform the calculation of c = 4 \ 2, which equals 2.
As mentioned earlier, division is one of the more complex arithmetic operators. You need to be aware of one condition that will always cause an error when dividing two numbers-dividing by zero:
2 / 0
This statement results in an error in VBScript. Most people know that it is impossible to divide by zero in the system of real numbers, and most programmers would never intentionally design code that divides by zero. Often, they simply fail to prevent it from happening or overlook cases where it could occur.
Note |
The error caused by the divide-by-zero calculation would cause VBScript to return a run-time error. See Day 17, "Exterminating Bugs from Your Script," for a detailed discussion of such errors. |
Consider the program in Listing 5.4, named speed.htm on the CD-ROM that comes with this book. This example shows a little application that calculates speed for a car or a runner. The user inputs the total distance traveled (in miles) as well as the amount of time it took to travel that distance (in hours). The program then calculates the speed in miles per hour by dividing the number of miles by the number of hours.
Listing 5.4. Speed calculation program that doesn't check for a divide-by-zero condition.
Sub cmdCalculate_OnClick()
Dim Distance
Dim TravelTime
Dim Speed
Distance = CInt(txtDistance.Value)
TravelTime = CInt(txtTime.Value)
Speed = Distance / TravelTime
txtSpeed.Value = Speed
End Sub
This code segment takes the distance and time from two text boxes, puts those values into variables, divides them, and places the result in another text box, as shown in Figure 5.4.
The program works fine as long as the user doesn't enter zero for the time. If she does, the program aborts with an ugly Divide by zero run-time error, as shown in Figure 5.5.
Figure 5.5 : The speed program crashes if the user enters a time of q!
One of the best ways to prevent divide-by-zero conditions is to perform simple checks in the code to block them. Listing 5.5, based on the Web page enhspeed.htm, shows a revised version of the speed calculator program.
Listing 5.5. Speed calculation program that checks for a divide-by zero condition.
Sub cmdCalculate_OnClick()
Dim Distance
Dim TravelTime
Dim Speed
Distance = CInt(txtDistance.Value)
TravelTime = CInt(txtTime.Value)
If TravelTime = 0 Then
MsgBox "The speed cannot be calculated because the time is zero. _
Please enter a valid time."
Else
Speed = Distance / TravelTime
txtSpeed.Value = Speed
End If
End Sub
If the user enters zero for the time, a message alerts the user that the speed cannot be calculated because the time to travel any distance cannot be zero. This case is shown in Figure 5.6.
Figure 5.6 : The speed calculator has been enhanced to avoid a divide-by-zero error.
This is one technique you can use to prevent a divide-by-zero error and in a wider sense, to make your programs more error free. Other useful techniques are presented on Day 17.
Exponents (^)
The exponent operator calculates a result based on the following formula:
result = number ^ exponent
The expression
Result = 2 ^ 3
evaluates to 8 because 2 * 2 * 2 = 8. The exponent function, which is available on most scientific and business calculators, is often used in formulas relating to science, engineering, and accounting. This function is one of several more advanced functions that will be addressed further in Day 16.
Modulo Arithmetic (Mod)
The Mod function is
another powerful arithmetic operator. Essentially, the Mod
function returns the remainder after dividing one number into
another. The syntax for the func-
tion is
Result = a Mod b
Consider what happens when you divide 2
into 5. The value 2
divides evenly into 5 twice
with a remainder of 1. If
you've ever performed long division, the expression would look
like this:
As you can see, the remainder is indeed 1. The Mod operator returns the remainder. In the expression
Result = 5 Mod 2
the return variable Result is equal to 1. The usefulness of this function will be explored further on Day 16. For now, just keep in mind that this is another arithmetic operator.
Negation (-)
The last of the arithmetic operators is the negation operator. Simply put, this operator changes the sign of a value contained in a variable or creates a negative number. For instance, the expression
Result = -2 * 3
results in assigning the value -6 to the variable Result. Likewise, the following lines of code produce the same result as the preceding line of code:
a = 2
b = 3
Result = -a * b
Notice that you can assign the negation operator to either a variable or a literal number. The negation operator is commonly used when you want to create a negative number or treat a positive number like a negative number.
Arithmetic Operator Precedence
Now that you have seen all the arithmetic operators that VBScript has to offer, you might be wondering how all the operators behave when put together in a single line of code. For instance, is the following line of code
2 * 3 + 6 / 2
equal to 9 or 6? When you combine arithmetic operators in an expression, you need to know the order of precedence of the operators. That is, what operations will the computer execute first as it moves from left to right across the expression? Table 5.1 summarizes the order of precedence for the arithmetic operators.
Exponents (^) | |
Negation (-) | |
Multiplication (*) and division (/ and \) | |
Modulo arithmetic (Mod) | |
Addition (+) and subtraction (-) | |
String concatenation (&) |
Notice that multiplication and division are on the same level of precedence. In this case, multiplication and division are executed in left-to-right order when it's their turn in the order of precedence. The expression
2 * 3 + 6 / 2
has three arithmetic operators: multiplication, addition, and division. As you can see in this table, multiplication is the first operation performed in the expression as you move from left to right. Both multiplication and division have the same order of precedence, so they are handled on a first-come, first-served basis. Because the multiplication is first, it gets executed first. As a result, the first operation in the expression is 2 * 3, which equals 6. This reduces the expression to
6 + 6 / 2
That leaves an addition operator and a division operator in the expression. Using Table 5.1, you can see that division has a higher order of precedence than addition does, so the division is handled next. The expression 6 / 2 equals 3, so the expression now becomes
6 + 3
Because only one operator remains, the choice is obvious-the result equals 9. VBScript follows this process of ordering an expression of multiple operators every time. When you are writing code, you must keep this order in mind.
One good way to maintain the order of expressions when writing and maintaining code is to designate subexpressions in parentheses. You can use parentheses freely in expressions, and they ensure that the subexpression will be fully evaluated first before it is evaluated as part of the larger expression. For example, you could write
c = 2 * 3 + 6 / 2
and c would evaluate to 9, as figured previously. You could also code the same expression as
c = (2 * 3) + 6 / 2
or
c = 2 * 3 + (6 / 2)
or even
c = (2 * 3) + (6 / 2)
and the results would still be the same: 9. However, with these statements, particularly the last one, the expression is much easier for a programmer to read and understand.
When using the parentheses approach, you must be aware of how subexpressions are evaluated. If you coded the statement as
c = (2 * 3 + 6) / 2
you get a result of 12 / 2 = 6 stored in c. The subexpression always gets evaluated first, which in turn affects the results of the overall expression. Because the human mind can digest information more easily by breaking it down into smaller pieces, subexpressions will make your code easier to follow and probably less error prone as well.
Comparison Operators
The first set of operators VBScript provides are arithmetic operators. This section discusses the second type: comparison operators. As the name implies, you use comparison operators to compare one or more variables, numbers, constants, or a combination of the three. VBScript has many different types of comparison operators, and each checks for a different comparison condition.
Equality (=)
You use the equality operator to see if a variable, constant, or number is equal to another. It's common to mistake the equality operator for the assignment operator, which is also represented by an equal sign. You use the assignment operator to set a variable equal to another variable, number, string, constant, or other data entity. For example, the statement
a = b
assigns the value contained in b to the variable a.
The equality operator, on the other hand, is used to test whether one value is equal to another. The syntax for the equality operator looks similar to that for the assignment operator:
a = b
where a and b
can be variables, constants, or numbers. It is the context in
which you use the expression that determines whether it is treated
as an assignment or an equality check. Equality is always used
in the context of checking a condition. For example, a statement
such as:
if a = b then
is an example of the equality operator because it is a conditional check. As a rule of thumb, you can assume that if a = b appears in a statement by itself, it is an assignment statement. If you see a = b as part of any other expression, it is used in the equality context.
If a does indeed equal b, the expression is true; otherwise, it is false. We have already been using the equality operator a great deal in the book so far. Refer to Listing 5.5, where you see the following section of code:
If TravelTime = 0 Then
MsgBox "The speed cannot be calculated because the time is zero. Â
Please enter a valid time."
Else
Speed = Distance / TravelTime
txtSpeed.Value = Speed
End If
This example uses the equality operator to see if the variable TravelTime is equal to 0. If it is, a set of instructions are executed, and if not, another set is similarly executed. You can also use the equality operator to check whether a variable is equal to a constant or even some other variable. You will see the equality operator used extensively throughout the book and in virtually any program. Likewise, you will also see the = symbol used as an assignment operator, where it actually assigns data to a variable. These are two of the most common operations in programming.
Inequality (<>)
Another important comparison operator is the inequality operator. You use this operator to test whether a variable is not equal to another variable or some data element. The syntax for the inequality operator is
a <> b
where a and b are variables, constants, strings, or numbers. Again, the expression returns True if the condition is indeed true and False if it isn't. For example, you could have taken the following code
If TravelTime = 0 Then
MsgBox "The speed cannot be calculated because the time is zero.
Please enter a valid time."
Else
Speed = Distance / TravelTime
txtSpeed.Value = Speed
End If
and made the following change, using the inequality operator rather than the equality operator, with the same results:
If TravelTime <> 0 Then
Speed = Distance / TravelTime
txtSpeed.Value = Speed
Else
MsgBox "The speed cannot be calculated because the time is zero.
Please enter a valid time."
End If
Sometimes, the inequality operator is more convenient and sensible to use than the equality operator. You will see such cases throughout the rest of the book.
Less Than and Greater Than (< and >)
You might have a condition where you don't care whether a variable is equal to another, but you do want to know whether it is greater than or less than another variable, number, or constant. In such a case, you need the greater-than and less-than operators. The syntax for these two operators is
a > b
and
a < b
where a and b are variables, constants, numbers, or strings, and the result is True if the expression is true. Otherwise, the expression returns False. For an example of its use, consider the following code:
If TravelTime > 0 Then
Speed = Distance / TravelTime
txtSpeed.Value = Speed
Else If TravelTime < 0 Then
MsgBox "You cannot enter a negative value for the time!"
Else If TravelTime = 0 Then
MsgBox "The time must be greater than zero!"
End If
Here, you see the greater-than, less-than, and equality operators all in use. If the variable TravelTime is greater than zero, a speed can be calculated, but if TravelTime is less than zero or equal to zero, the user must be notified-any such value would not be valid.
You could write the same code in another way if you carefully think about the conditions being satisfied. If a travel time is not greater than zero and not less than zero, you know it must be zero. Even without checking for this value, you can tell that is the only possibility left! You could therefore rewrite the code as
If TravelTime > 0 Then
Speed = Distance / TravelTime
txtSpeed.Value = Speed
Else If TravelTime < 0 Then
MsgBox "You cannot enter a negative value for the time!"
Else
MsgBox "The time must be greater than zero!"
End If
This code works just as well as the previous code. The first method was used to emphasize the purpose of the equality expression. The first method is also a better approach in some respects, because with the conditions explicitly named, the purpose of each branch of the code is more clearly defined and easier to read and debug. Code that is clearer is usually also easier to maintain and less subject to bugs.
Less Than or Equal To and Greater Than or Equal To (<= and >=)
Sometimes, you also might want to see whether a variable is greater than or equal to some other variable, constant, or number. Perhaps you want to know if it is less than or equal to the entity. Then, you can combine operators to use the less-than-or-equal and greater-than-or-equal operators, <= and >=. The syntax for these operators is
a <= b
and
a >= b
The expression returns True or False, depending on whether the expression is true. Suppose you take the code shown in the previous section and change it to
If TravelTime > 0 Then
Speed = Distance / TravelTime
txtSpeed.Value = Speed
Else If TravelTime <= 0 Then
MsgBox "You cannot enter a negative value or zero for the time!"
End If
This code combines the conditions of a zero time and a negative time into one simple check. Because both cases are invalid, it makes the code simpler to perform one check. It is more useful to the user to know whether a zero or a negative value was entered, but because both are invalid, you might not consider that very important. In any case, these conditional checks can tell you whether a condition is True.
Again in this example, you could write the code to simply use an else as the last condition because you know if a time isn't greater than zero, it must be less than or equal to zero. However, as in the earlier example, the explicit approach helps illustrate the use of the <= operator and also makes clearer code.
Object Equivalence (Is)
The last comparison operator is designed for objects, which are discussed in more detail on Days 8, "Intrinsic HTML Form Controls," through 11, "More ActiveX Controls." For now, consider an object such as a command button that you can place on a Web page. The syntax of the Is operator is
result = object_reference1 Is object_reference2
where object_reference1 and object_reference2 are references to objects and result is either True or False, depending on whether the statement is true.
This operator does not compare one object to another, nor does it compare values. This special operator simply checks to see if the two object references in the expression refer to the same object. Suppose, for example, you have included a command button in your script you have defined as TestButton. You have another variable, myObject, that is set to reference different objects at different points in your program. Assume that a statement has been carried out that assigns the variable myObject to reference this button, such as
Set myObject = TestButton
If the script later carries out the expression
result = myObject Is TestButton
it will return the True in the variable result because TestButton is indeed the same object as that referred to by myObject. If, on the other hand, you were to enter
result = myObject Is SomeOtherTestButton
result would be False because the two objects are not the same.
As you can see from this discussion, there are some special rules for dealing with objects. You must use the Set statement to assign an object's value. And you cannot directly compare two objects with an equal statement, such as
if myObject = TestButton ' illegal syntax
The sample page objcomp.htm on the CD-ROM that comes with this book illustrates some of these concepts. You'll learn the nuances of objects in the days ahead. For now, it is just important to realize that among the full range of operators covered today, the Is operator is available for object equivalence checks.
Comparison Operator Precedence
Unlike arithmetic operators, comparison operators do not have a specific order of precedence. They are simply executed as they are found from left to right across an expression. When VBScript encounters an expression such as
If 3 > 5 < 10 Then
VBScript will evaluate the conditions in the order they appear from left to right. In this case, the part of the expression that comes first, 3 > 5, is evaluated first as False. False in VBScript is equivalent to 0, so the expression becomes
If 0 < 10 Then
Because 10 is greater than 0, the expression is True. As a result, the entire expression is True and whatever code follows this if-then expression will be executed. Conditional expressions will be discussed more fully on Day 6, "Controlling the Flow of VBScript Code."
Logical Operators
The last category of operators in VBScript is logical operators. The logical operators might require a more significant amount of understanding to appreciate. In some cases, the way you use logical operators seems to run counter to your intuitive thinking. If you've ever taken a course in logic, you have first-hand experience with this. Because logical operators are such an important part of VBScript, it's important to gain a good understanding, starting with the basics, so that you can use them effectively.
Logical operators use the binary number system to represent information. The part of the binary number system used in this lesson is very simple: Expressions evaluate to True or False, respectively. The logical operators discussed in this section are designed for binary numbers, not decimal numbers. The binary number system counts in units of two rather than ten, so it's quite different from the decimal system. It is beyond the scope of this book to explore all the details of the binary number system. If you are interested in learning more about the binary system, you can refer to any introductory computer science principles textbook. If you are not familiar with binary numbers, simply remember that True and False are the only values used with logical operators. A logical expression, such as
5 > 3
is a true statement and would return True if evaluated. If you inspect the value of True, you would see that it contains the true indicator of -1. It turns out that -1 is a convenient way to represent True internally in the binary system upon which your computer and VBScript are based. If you need to convince yourself that this is really the representation, you can try a quick test within a Web page script. Simply insert code like the following:
<SCRIPT LANGUAGE="VBScript">
' True condition, this will display "True"
msgbox (3 = 3)
' VBScript integer representation of True condition, this will display "-1"
msgbox cint(3 = 3)
' False condition, this will display "False"
msgbox (3 = 2)
' VBScript integer representation of False condition, this will display "0"
msgbox cint(3 = 2)
</SCRIPT>
As soon as your page is loaded, this script code will be launched. You will see a series of four message boxes. The first two expressions, based on (3 = 3), are true statements, of course. The first message box displays the VBScript text indicator of a true condition, True. The second message box uses the Cint function to obtain the integer equivalent of this condition, which shows up as -1. Similarly, the next two statements display False and 0 because the condition (3 = 2) is false. You can always use the intrinsic VBScript constant True to represent the true condition. Likewise, you can always use the intrinsic constant False to represent the false condition. If you were to display the integer value of the constants, you would see that they are similarly associated with -1 and 0, respectively. With that understanding of how Visual Basic handles true and false conditions, take a look at the suite of logical operators.
Negation (Not)
The first operator is called the negation operator. This operator has the following syntax:
result = Not expression
Table 5.2 shows the result
variable in relation to expression.
If expression is… | then result is… |
True | False |
False | True |
Null | Null |
If you enter the expression
a = Not 1 > 2
where the expression is 1 > 2, the result is stored in the variable a. The value stored in variable a will be True. The expression 1 > 2 is false because 1 is not greater than 2. Not simply flips a false over to true or a true over to false. Because the expression is false, the Not operator makes the result true. As a result, the VBScript value for true, True or -1, will be stored in variable a. If the expression is null, the Not operator will return a null when applied to the expression.
Where might you use the Not operator? It is often used when working with if-then conditionals. Consider, for instance, the following code segment:
If GetZip(City, State, Zip) = False Then
MsgBox "The zip code could not be determined."
Else
MsgBox "The zip code is " & Zip
End If
This simple example calls the function GetZip. The arguments for this function are the city, state, and zip code. The function returns a Boolean value that indicates whether the function has succeeded. This return variable is often called a return code. The function loads the variable Zip with the zip code and returns True if it is successful. If the function fails, it returns False. The function could fail, for example, if an invalid state or city was passed as an argument to the function.
The conditional statement checks the return code. If it is true, the function has succeeded and the code proceeds to show the user the zip code. You could use the Not operator instead, in which case the code would look like this:
If Not GetZip(City, State, Zip) Then
MsgBox "The zip code could not be determined."
Else
MsgBox "The zip code is " & Zip
End If
The only difference is that you use the Not operator instead of the equality operator. In some cases, this makes the code easier to read. In other cases, such as the following:
GetZipFailure = Not GetZip(City, State, Zip)
the Not operator is necessary. If GetZipFailure is a variable that contains the failure status of the call, Not is the most convenient way to map the return value of the function to the variable. More uses for this operator will become apparent as you see more code examples.
Conjunction (And)
The conjunction operator compares two or more variables in some type of test. The syntax for the conjunction operator is
result = expression1 And expression2
Table 5.3 shows the result variable in relation to expression1 and expression2.
If expression1 is… | and expression2 is… | then result is… |
True | True | True |
True | False | False |
False | True | False |
False | False | False |
In order to obtain True in the result variable, both expression1 and expression2 must be true. You often use this operator to make sure two or more conditions are true before performing some action. Suppose you have a Web page for making airline reservations. You have several functions in your code: one to get the customer's name and address, one for the origination point, one for the destination, and one for the day he wants to travel. In order to book the reservation, each function must succeed. If any of them fail, the reservation cannot be made. The following statement is an example of what could appear in a VBScript code segment:
OkayToReserve = _
GetCustomer(Name, Address, Phone) And _
GetDepartureCity(DepartCity) And _
GetDestinationCity(DestinationCity) And _
GetTravelDate(TravelDate)
If the function that gets the destination city from the customer, for example, does not succeed for whatever reason, your program will not accept the reservation.
This example is simple, but you get the point. Each of these functions must return True. If any one of them fails, the variable OkayToReserve will be false. You can then make a simple check to determine whether to make the reservation:
If OkayToReserve = True Then MakeReservation( Name, Address, Phone, _
DepartCity, DestinationCity, TravelDate )
You can use the conjunction operator for a lot of other purposes. As you progress through the book, you will see more examples of its use.
Note |
VBScript lets you take a shortcut when referencing true in a condition. You don't have to explicitly compare the condition to true. If you have no comparison, it assumes you are checking the true condition. The following statement is functionally equivalent to the previous example without using the True constant: If OkayToReserve Then MakeReservation( Name, Address, Phone, _ DepartCity, DestinationCity, TravelDate ) |
Disjunction (Or)
Another frequently used logical operator is the disjunction operator. This operator has the same syntax as the conjunction operator:
result = expression1 Or expression2
Table 5.4 shows the result variable in relation to expression1 and expression2.
If expression1 is… | and expression2 is… | then result is… |
True | True | True |
True | False | True |
False | True | True |
False | False | False |
This operator behaves quite a bit differently from the conjunction operator! In this case, any of the expressions can be true for the result to be true. The result is false only if all the expressions are false. You typically use this operator when you have to make a decision where any of a number of activities could occur, but only one must occur for the operation to proceed. Suppose you want to call a function on your Web page that processes an order for flowers. If you have five varieties of flowers, the customer could order one or more types. You simply want to see if any of them are on order. All it takes to process an order is a request for one type. The following code segment would handle this for you:
If Order1 Or Order2 Or Order3 Or Order4 Or Order5 Then
OrderFlowers()
End If
In this case, five variables exist that are true or false, depending on whether the user wants to order flowers of that type. If the user wants to order flowers of any type, the script calls the OrderFlowers function. That function can then determine the specifics of the flower order.
Exclusion (Xor)
The exclusion operator is another in the family of logical operators that you can use to make decisions based on the contents of one or more expressions. It checks whether one and only one condition is exclusively true. The syntax of the exclusion operator is
result = expression1 Xor expression2
Table 5.5 shows the result variable in relation to expression1 and expression2.
If expression1 is… | and expression2 is… | then result is… |
True | True | False |
True | False | True |
False | True | True |
False | False | False |
If you compare Table 5.5 to 5.4, you'll see that these operators differ in only one way. With the Or operator, if either or both expressions are true, the result is true. With the exclusion operator, however, if all the expressions in the statement are the same-that is, all true or false-the result is false. Only when they are different is the result true.
Logical Equivalence (Eqv) and Implication (Imp)
The remaining two logical operators are Eqv and Imp. The equivalence operator checks whether two expressions are bitwise equivalent to each other. The syntax is
result = expression1 Eqv expression2
The Imp operator performs a logical implication on two expressions. The syntax for that operation is
result = expression1 Imp expression2
If you're a very experienced programmer, you know what Imp and Eqv do, and you're probably glad to see them in the VBScript repertoire. However, if you're a beginner, you might be thinking at this moment, "What on earth is bitwise equivalence and logical implication?"
Like all the logical operators covered here, the Imp
and Eqv comparisons are performed
on a bit-by-bit basis and the results are set on a bit-by-bit
basis. For the other operators, the functionality it provides
and the expected results are intuitively obvious. For Imp
and Eqv, the results are
less intuitive. Of course, any expression is ultimately represented
in bits on a computer, and to understand these operators, you
must think in terms of these bits. Picture a comparison on two
numbers, analyzing them each bit-by-bit and setting the result
expression bit-by-bit according to the rules in Tables 5.6 and
5.7.
If expression1 is… | and expression2 is… | then result is… |
True | True | True |
True | False | False |
False | True | False |
False | False | True |
If expression1 is… | and expression2 is… | then result is… |
True | True | True |
True | False | False |
False | True | True |
False | False | True |
Most types of programs use these operations infrequently, so they are typically the realm of advanced programmers. I do not outline them here in detail. You can refer to any computer science text for more details on the binary numbering system and bitwise operations to gain a full appreciation of how to use Imp and Eqv. It is important to realize that the language does provide the capability to carry such operations in case you sometime need to analyze data at this level.
Logical Operator Precedence
Like arithmetic operators, logical operators have an order of preference, shown in Table 5.8.
Operation | |
Negation (Not) | |
Conjunction (And) | |
Disjunction (Or) | |
Exclusion (Xor) | |
Equivalence (Eqv) | |
Implication (Imp) |
Any type of operator is evaluated from left to right in an expression. For an example of logical operator precedence, consider the following code statement:
If a Xor b And c Or d Then
For this example, suppose a is true, b is false, c is false, and d is false. Moving from left to right, you have the operators Xor, And, and Or. Because And gets first precedence, the expression b And c is evaluated first. The result of False And False is False. As a result, the expression becomes
If a Xor False or d Then
Now, moving from left to right, the two operators are Xor and Or. Or is next in the line of precedence, so the next expression up for evaluation is False Or d. Because d is false, False Or False equals False. The expression becomes
If a Xor False Then
Now, Xor is the only operator left. Because a is true, True Xor False is True. As a result, the expression reduces to
If True Then
which means the code that follows the if-then statement will be executed. It is very important to understand the order of precedence when you have more than one expression connected together in a single statement. Make sure you walk through your code and know what it's doing before you turn your attention from this kind of code statement.
Working with Strings
One special operator does not fit in any of the other classes. This operator, called the string concatenation operator, is represented by the & symbol. You have already seen strings at work on Day 4, and you will learn more about them in this section. For complete coverage of how strings work, Day 15, "Extending Your Web Pages with Strings," describes all the essentials of string creation, manipulation, and use. We also cover the string concatenation operator here so that you learn all the operators in the VBScript suite.
String Concatenation (&)
You use the string concatenation operator to merge two strings together. If, for example, one variable holds the string
First_Name = "Buddy"
and the second holds the string
Last_Name = "Bird"
to form a complete name, you would want to concatenate these two strings together. You could accomplish this with the concatenation operator. The syntax for this operator is
result = string1 & string2 & ... & stringn
Note that you can concatenate any number of strings on the same line of code. If you want to concatenate the first and last names, your first instinct would be to enter
Name = First_Name & Last_Name
Oops! If you check the name, you find that the string becomes "BuddyBird". You need to insert a space. No problem-you can simply add the space string right into the expression:
Name = First_Name & " " & Last_Name
Note that you can concatenate strings contained in variables as well as literal strings in one, single expression. Now, if you check the Name variable, the stored result should be
"Buddy Bird"
String Concatenation Using the + Operator
You should know one more thing about string concatenation. As you begin to see examples of VBScript code on the Internet, you might from time to time see strings concatenated using the + operator rather than the & operator. For example, you can build a name with this code:
Name = First_Name + " " + Last_Name
This statement would correctly build the string "Buddy Bird" for you. Although you can indeed use the addition operator to concatenate strings, you're not always guaranteed a correct result because the addition operator is designed for numeric values. It can handle strings, but when strings are mixed with numbers, VBScript can get into an ambiguous state, not knowing exactly how you want to concatenate the values. If, for example, one of the expressions is a number and the other is a string, the + operator gives you an error:
Dim a, b, c
a = 10
b = " Apples"
c = a + b
MsgBox c
When VBScript encounters the expression c = a + b, a type mismatch error will result. You're trying to add a number and a string that cannot be translated into a number. Instead, you should use
Dim a, b, c
a = 10
b = " Apples"
c = a & b
MsgBox c
and you will store "10 Apples" in the variable c. Table 5.9 shows you the rules for whether the + operator concatenates or adds, depending on the subtype of the variable or variables in question.
Both expressions are numeric | Add | 10 + 2
15.6 + 3 -6.2 + 18 |
Both expressions are strings | Concatenate | "Ten" + " Apples" "Going " + "shopping" |
One expression is numeric and the other is a string that can be converted to a numbe | Add | 10 + " 110" 100 + " 25 " |
One expression is numeric and the other is a string that cannot be converted to a number | Error! | 10 + " Apples" 100 + " Dalmatians" |
Notice that you must enclose literal numbers in quotes if you want to treat them as strings when you concatenate them to other strings. Because this is not very convenient and requires extra thought, it's safer and better to use the & operator whenever you're concatenating strings. This helps reduce potential errors in your code-always a wise decision.
You can do a great deal more with strings in VBScript. On Day 15, you will learn even more about strings, along with many supporting functions that let you handle strings in flexible, powerful ways. Until then, I'll just show you string concatenation and save the more advanced concepts for later.
Operator Precedence
Now you have seen all the operators VBScript has to offer. For each type of operator-arithmetic, comparison, and logical-you have seen the order of precedence. What happens when operators from different categories are all combined in the same statement? What is executed first?
VBScript first attends to the arithmetic operators, followed by the string concatenation operator, the comparison operators, and the logical operators, as summarized in Table 5.10.
Exponents (^) | ||
Negation (-) | ||
Multiplication (*), division (/ and \) | ||
Modulo arithmetic (Mod) | ||
Addition (+), subtraction (-) | ||
String concatenation (&) | ||
Equality (=) | ||
Inequality (<>) | ||
Less than (<) | ||
Greater than (>) | ||
Less than or equal to (<=) | ||
Greater than or equal to (>=) | ||
Object equivalence (Is) | ||
Negation (Not) | ||
Conjunction (And) | ||
Disjunction (Or) | ||
Exclusion (Xor) | ||
Logical equivalence (Eqv) | ||
Implication (Imp) |
When an expression has more than one operation, each part of that expression is evaluated in this order from left to right across the expression.
If you want to force VBScript to target a specific part of a code statement, you can use parentheses as discussed earlier today. For example, suppose you have the statement
x = 6 * 5 / 2 - 5 + r
in your code. In normal circumstances, the variable x would be expressed as
x = 10 + r
where the expressions would be evaluated in the following order:
x = 6 * 5 / 2 - 5 + r
= 30 / 2 - 5 + r
= 15 - 5 + r
= 10 + r
x = 10 + r
If r is 5, the answer is
x = 10 + 5
x = 15
Suppose you wanted to treat the expression 5 + r as a single entity. You would simply put parentheses around 5 + r:
x = 6 * 5 / 2 - ( 5 + r )
which would result in the following order:
x = 6 * 5 / 2 - ( 5 + r )
= 30 / 2 - ( 5 + r )
= 15 - ( 5 + r )
=
x = 15 - ( 5 + r )
If r is 5, the answer is
x = 15 - ( 5 + 5 )
x = 15 - 10
x = 5
The difference in results is due to the parentheses around part of the expression, which can have a dramatic impact on the results. For another example, suppose you had to calculate the sales tax on a customer's order where you had the cost of two items. Call the cost of the first item x and the cost of the second item y, and say the sales tax is 6 percent of the total cost. You could write this expression as
tax = x + y * 0.06
but it would be incorrect. If you follow the order of precedence,
y * 0.06 would be evaluated,
and the result would be added to x.
This is not what you want. Rather, you first want x
and y to be added and then
multiplied by 0.06. The order of precedence is getting in your
way, preventing you from obtaining a correct result. In this case,
you have to force VBScript to do the addition first and then the
multiplication. To do this, you simply enter the
expression as
tax = (x + y) * 0.06
which will give you the correct result. Because the expression x + y is in parentheses, VBScript will evaluate it first and then multiply the total cost by the sales tax. The order of precedence is a very important part of handling expressions.
Summary
Today's lesson presents you with the entire suite of VBScript operators. Operators are the workhorses for variables; they put variables to work by making decisions and changing their contents. A fundamental knowledge of operators is necessary in understanding VBScript from top to bottom.
Operators fit into three separate categories: arithmetic operators, comparison operators, and logical operators. Each of these categories has a special use in a VBScript program. Today you have learned about all the operators in these three categories and saw examples of how to use each of the operators in your programs. You have also seen how operators can work together to accomplish a result. Operators are executed in a specific order when they are combined. Programmers must take this order into account when they write code. Today's lesson clearly lays out this order of precedence so that you know what to expect when using the operators presented today.
Today you have been introduced to concepts that will be addressed more thoroughly in upcoming days. As you venture deeper into the realm of VBScript programming, each day will build on the previous. Carefully consider the quiz questions because they will help prepare you for the exciting lessons to come.
Q&A
What are operators? | |
Operators are symbols used in VBScript that perform some specific task. Operators come in three varieties: arithmetic, comparison, and logical. Arithmetic operators handle math operations such as addition and multiplication. Comparison operators help in comparing one variable to another. Logical operators are used in making decisions based on expressions that are either true or false. | |
What do operators operate on? | |
Operators can operate on variables, literal numbers, constants, or entire expressions. | |
Why are operators important? | |
Operators are important to programmers because they are used to make decisions, assign data to variables, and control the flow of programs. | |
Are some operators more important than others? | |
VBScript ranks the operators in a specific order, called the order of precedence. The order of precedence helps determine how a code statement is executed when it has more than one operator. |
Workshop
Design a Web page that asks the user for a series of values. Store those values in variables and write code that exercises every one of the operators discussed today. Which ones are you the most familiar with? Which ones do you anticipate using the most in your Web pages?
Quiz
Note |
Refer to Appendix C, "Answers to Quiz Questions," for the answers to these questions. |
- Write a program that converts feet to inches. Hint: There are 12 inches in a foot.
- Write a program that sells concert tickets to your customers. Get from the customer her name, how many tickets she wants, and whether or not she wants front-row tickets. Use the following formula in calculating the cost: Ticket cost equals $20.00 plus $4.00 for front row tickets plus a 3% commission. Add 8% sales tax to the total cost of the ticket plus the commission.
- Determine the result of the following expressions using the
order-of-
precedence rules:
a. 5 * 9 - 3 ^ 2
b. (72 - 3) / 3 Mod 3
c. 7 + 2 - 5 * 2
d. True Or False And True
e. False Or Not True