Working with variables
Variables are used to save a value. This value can change during the execution of the code, but we can use the value over and over again by stating the name. In most programming languages a variable has a datatype. In ASP this isn't the case, all variables are of the type Variant (VBScript). A variable does have an implicit subtype. This can lead to strange things because for example a number with a text that states a number will be compaired, even though they aren't the same for the programm.
The sample below illustrates the use of variables. A value will be made and then it will be written to the browser:
vars1.asp
<HTML>
<BODY>
<%
MyVar = "Hello world!"
Response.Write(MyVar)
%>
</BODY>
</HTML>
In the sample above the variable is used without defining it first. While this is possible, is does have a serious disadvantage. If you'd make a typing error, the result would be incorrect. Imagine you
would have written Response.Write(MyVa). ASP would consider MyVa a new variable and nothing would appear in the browser. Therefore it's usefull to make it obligatory to declare the variables first. You can do this by placing theOption Explicit as the first line in the script.
After that every variable has to be named with the
Dim statement.
vars2.asp
<%Option Explicit%>
<HTML>
<BODY>
<%
Dim MyVar
MyVar = "Hello world!<br>"
Response.Write(MyVar)
MyVar = " This script uses Option Explicit"
Response.Write(MyVar)
%>
</BODY>
</HTML>
If we would make the mistake discussed earlier in the code above, ASP would give an error message that tells tou that
the MyVa variable hasn't been declared.
|