More Easy Stuff - Page 3
February 5, 2001
Operators and Expressions
Continuing with our very down-to-earth approach to technical
terms, an operator is something that can be used to perform
operations (like arithmetic, comparisons and logical) on
variables. Operators are used within expressions, or anything
that can be evaluated by the computer to produce an outcome, i.e.
some value. For example, 1 + 1 is an expression. The outcome is
the value 2. Guess what? The + sign is the operator! Let's take
a look at some other operators in an ASP environment.
<%
Dim X, Y
Dim A, B, C
X = 5
Y = 10
X = X + Y
'X now equals 15
Y = X / 2
'Y now equals 15 divided (/) by 2, or 7.5
A = X
B = Y
C = (A * B)^2
'C now equals A times (*) B or 15 times 7.5
'This is done first because it is in parenthesis.
'Then that number (112.5) is raised to
'the 2 power (^ is exponentiation).
'C ends up equaling 12656.25
%>
Most of the code in the block above is commented to show you
exactly what happens. However, let's talk about a few key points.
First, you will notice that the first thing I did with the
variables was to give them a value of some sort. X
was set equal to 5 (using, you guessed it, the equality operator)
and Y was set equal to 10. Only then was an
arithmetic operation performed on them (X + Y). If I
had tried doing X + Y without giving them any
particular value then it would have been completely confused and
not known what to do, returning an ugly error. What is the moral
of the story? If you want to perform operations on variables then
make sure they contain some value on which it makes sense to
perform the operation you are considering.
Also, when writing expressions make certain you consider Pretty
Please My Dear Aunt Sally ... or in technical terms, operation
precedence. The way you order your operations will have a
significant impact on the outcome of the expression —
X*Y^2 is very different then (X*Y)^2.
Basic stuff: exponentiation comes before parenthesis which comes
before multiplication, division, subtraction, and division; all
of which is read left to right. When dealing with expressions
that contain arithmetic, comparison and logical operators,
arithmetic are treated first, then comparison and finally
logical. Just experiment with some simple math equations that
you can check on a calculator to get some experience with this
stuff. Below is a table from Microsoft listing the different
operators in VBScript.
Source: Microsoft Scripting Technologies
VBScript - The Easy Stuff - Page 2
Back to Basics: VBScript for ASP
Doing Stuff - Page 4
|