ASP Subs and Functions

Classic ASP organizes reusable VBScript code into Sub procedures, which perform an action but return nothing, and Functions, which compute and hand back a value you can use in an expression.

Subs: Sub ... End Sub

A Sub performs one or more actions — like writing output, updating a variable, or looping — but does not hand back a result. Define one with Sub name(parameters), write the body, and close it with End Sub. You call a Sub either with the Call keyword and parentheses, or by writing its name followed by any arguments without parentheses.

Example

<%
  Sub GreetVisitor(visitorName)
    Response.Write("<p>Hello, " & visitorName & "! Welcome back.</p>")
  End Sub

  Call GreetVisitor("Meera")
  GreetVisitor "Devan"
%>

Functions: Function ... End Function

A Function is defined almost the same way, using Function name(parameters) ... End Function, but it produces a value: somewhere inside the body you assign a result to the function's own name, and that becomes what the function evaluates to when called. Because a Function returns a value, it can be used directly inside an expression, an If condition, or a Response.Write call — something a Sub can never do.

Example

<%
  Function Square(n)
    Square = n * n
  End Function

  Dim result
  result = Square(6)
  Response.Write("6 squared is " & result)
  Response.Write("<br>4 squared is " & Square(4))
%>

Passing Arguments: ByRef vs ByVal

By default, VBScript passes arguments ByRef, meaning the procedure receives a reference to the original variable — if the procedure changes the parameter, the caller's variable changes too. Marking a parameter ByVal instead gives the procedure its own private copy, so changes made inside the procedure never affect the caller's variable.

Example

<%
  Sub AddTax(ByRef price)
    price = price * 1.1
  End Sub

  Dim cost
  cost = 100
  AddTax(cost)
  Response.Write("Price after tax: " & cost)
%>
SubFunction
Returns a valueNoYes
Can be used inside an expressionNoYes
Declared withSub ... End SubFunction ... End Function
Typical usePerform an action (print, update, loop)Calculate and hand back a result
Note: A common convention is to name Subs with a verb describing the action (GreetVisitor, LogError) and name Functions after the value they produce (Square, FormatPrice), which makes calling code easier to read.

Exercise: ASP Procedures

What is the main difference between a Sub and a Function in VBScript?