Functions and subprocedures have many similarities:
They can be called or invoked from anywhere within your script. A function or subprocedure can be reused as many times as required, thus saving you time writing out repetitive code and making for a less clustered looking page.
Both are blocks of self contained code that can accept arguments. Both will only run when called or invoked from code elsewhere and will not run automatically when the page is loaded.
The difference between a function and a sub is that a sub will do some stuff (like printing something to the screen) and then quit, while a function runs some code and then returns the result back to the code that called it. A Function could be used to do a calculation and then return a result.
How to declare/write each:
<%
Sub NameOfSubRoutine(parameter1, parameter2)
'code goes here...
End Sub
%>
<%
Function NameOfFunction(parameter1, parameter2)
'code goes here
NameOfFunction = "return value"
End Function
%>
You will notice above parameter1 and parameter2. Data is passed
into a procedure through the use of these arguments. Arguments are
separated by commas and put into parenthesis after the procedure
name.
If there are no arguments, the procedure would still have the parenthesis,
but they would be empty as our example below shows:
<%
Sub NameOfSubRoutine()
'code goes here...
End Sub
%>
Below is a subprocedure that prints out details on the page:
<%
Sub PrintOut(name,address,country)
response.write name
response.write address
response.write country
End Sub
%>
To call the Sub, I could do one of the following:
<%
Call PrintOut("michael","34
Hark Avenue","Ireland")
%>
OR
<%
PrintOut "michael","34 Hark Avenue","Ireland"
%>
Note that in each example, the actual argument passed into the
subprocedure is passed into the subprocedure in the corresponding
position.
Also note that if you use the Call statement, the arguments must
be enclosed in parenthesis. If you do not use call, the parenthesis
aren't used.
Like the Sub procedure, a Function can accept arguments, but unlike the Sub procedure, a Function can return a value. Functions are especially good for doing calculations and returning a value.
<%
Function Total(firstnumber,secondnumber)
Total=(firstnumber+secondnumber)
End Function
%>
This is how the function was called:
Calling the Total function made the value of Total equal to the value returned by the function, which then can be displayed by doing
The output of the above is: 102
Note that the returned value is named the same as the function.
This is important to remember! You will need to name the output
value the same as your function or you will not get a value returned.
Get the best asp web hosting provider now and save 30%
Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.