CIS 209 Web Page Scripting Languages

Chapter 6: Functions and Procedures

In this chapter we will learn how to call JavaScript and VBScript functions and procedures that can be reused to change the order in which action statements are executed.

Built-in Functions and Methods

When an object contains a built-in function it is referred to as a method. Built in functions include mathematical, date and time, string and formatting functions. Some are common to both JavaScript and VBScript, and some are unique to that scripting language.

JavaScript Math Object Methods

JavaScript includes a built-in math object which exposes many mathematical methods. As we've learned, a method is a function that is defined within an object. To access the abs method of the Math object, we can use the syntax: Math.abs(). The table below identifies several of the common mathematical methods that JavaScript supports.

Method      Description ExampleResult   
AbsReturns the absolute value of a numberMath.abs(-2)2
Floor Rounds number to next lowest integer Math.floor(7.1) 7
Ceil Rounds number to next highest integer Math.ceil(7.1) 8
Random Returns a random number between 0 and 1     Math.random() varies
Round Rounds the number to the nearest integer Math.round(7.5)     8
MinReturns the lowest of two numbersMath.min(3,4)3
MaxReturns the highest of two numbersMath.max(3,4)4

The following code uses the random method of the math object to select a random number between 0 and 1.

<script language="javascript">
var randNum=Math.random();
document.write(randNum);
</script>

Check out the EXAMPLE.

JavaScript String Object Methods

In the past, we've assigned a string to a variable with varName="Sam". We can explicitly define a string object with the keywords new String. Here's an example: varName=new String("Sam"). The string object exposes several built-in properties and methods.

The length property returns the number of characters in the string. The toLowerCase method converts the string to all lowercase letters. In the following example, we will demonstrate how the toLowerCase method can be used to convert a string to all lower case letters. Note that the string is not passed as an argument, but it is the object that is invoking the method. Thus, we use objectName.method().

<script language="javascript">
var myPWD="PassWord";
var myNewPWD=myPWD.toLowerCase();
document.write(myNewPWD);
</script>

or we could have used the following single line of code:

document.write("PassWord".toLowerCase());

See table 6-2 in our text for other Common Methods of the String Object on page 215.

The toString Method

The toString method belongs to several objects, including the string, number and math objects. The toString function can be used to convert a number to a string. The EXAMPLE demonstrates how to use the toString method to convert a number, math and string object to a string. At the bottom, it shows how to convert a function to a string.

JavaScript Global Functions

When a value is passed from a form, the value is a string. You cannot perform mathematical calculations on strings. Whether we're using VBScript or JavaScript, you will need to convert string variables and strings to numbers.

In JavaScript, there is a global object that contains functions that are not associated with other JavaScript objects. The functions within the global object can be accessed without creating an instance of the global object. These functions include eval, isNaN, parseInt and parseFloat.

The Eval Function

The eval function of the global object will evaluate a string of JavaScript statements and return the result. If the argument passed to the eval function is a number, then the results will be returned as a number.

The eval function is useful when you receive a number as a string object from a form, and need to convert it back to a number. Check out the following EXAMPLE which illustrates how the eval function can be used to convert form field values to a number.

The isNaN Function

The isNaN function in JavaScript is known as the "is not a number" function. If we attempt to use a nonnumeric value in a mathematical equation, the script will cause an error. We can use the isNaN function to determine whether a value is something other than a number. It helps us avoid errors.

The isNaN function returns false if a value is a number, or true if the value is not a number. Check out the EXAMPLE.

The ParseInt and ParseFloat Functions

The parseFloat function converts a string into a floating-point number. The parseInt function converts a string into a number. The parseInt function takes two parameters, the string and the radix. The radix identifies which base numbering system you want to use; 2 for binary numbering system, 16 for the hexadecimal numbering system, and 10 for the decimal numbering system. Since the default radix is base ten for decimal numbering system, the radix does not have to be explicitly stated.

We do not have to convert a string in JavaScript if it contains only numbers - Even if it has leading or trailing blank spaces. For example, if a variable X was equal to "   7      ", Y was equal to 3, and we had a formula Area=X*Y, Area would be displayed as 21.

VBScript Built-in Functions

In VBScript the isNumeric function is used to determine if a value of a variable is numeric or not. Check out the EXAMPLE.

VBScript supports additional built-in data conversion functions such as cInt, which converts a string to an integer. Also, VBScript supports the formatCurrency function which formats a number as currency. VBScript contains several built-in date and time functions that are used to retrieve information about a specific date, and functions that can manipulate strings. The len function returns the number of characters in a string.

See table 6-3 in our text for other Common VBScript Built-in Functions on page 220. Check out Microsoft's web site for a complete list at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/vtorifunctions.asp.

VBScript includes two built-in functions that display information within the browser. The InputBox function is similar to the JavaScript prompt window. And the MsgBox function is similar to the JavaScript alert window. Don't forget that Netscape does not support VBScript! This means that we really should use JavaScript for all client-side scripts. We can use VBScript for server-side scripts since the functions are executed on the server.

Using Functions

A function is a block of code that is grouped into a named unit. The function is identified by a unique name. Both JavaScript and VBScript use the keyword function to identify the start of a function, with a pair of parentheses following the name of the function to pass arguments or parameters to the function.

Both functions and procedures can accept several arguments. Functions in VBScript can be public or private. Public functions are visible to all other functions in the script. Private functions are only available within the script in which they are declared. The keyword public is optional. If a function is not declared public or private, it is public by default. We use the word public or private just before the function keyword.

In JavaScript, the block of code is enclosed in a pair of curly braces { }. VBScript uses the keywords end function to identify the end of a function since VBScript does not use the curly braces as JavaScript does.

A function can return a value to the script that called it. If it returns a value, only one value can be returned. VBScript uses the keywords exit function to exit a function. Exit function is an example of a jumping control that allows you to temporarily halt the execution of block of code and move to a different section of code.  The keywords exit function appear as an action statement. The syntax for creating functions in JavaScript is:

function FunctionName(argument1, argument2, etc.){
      action and control statements;
      return returnValue;
}

And the syntax for creating functions in VBScript is:

[Public | Private] function FunctionName(argument1, argument2, etc.)
      action and control statements
      FunctionName=returnValue
end function

The function is called by another part of the script. The function must be created before it is called. For this reason, functions are often defined in the <HEAD> section of a Web page. Functions are similar to procedures in that they can both make calls to themselves. To call a function in JavaScript, use the syntax:

FunctionName(argument1, argument2, etc.)

A VBScript can use the optional keyword call to call a function. If the keyword call is used, the arguments passed to the function must be enclosed in parentheses. If no arguments are passed, you do not have to use parentheses. When the keyword call is used to call a user-defined function, the return value is discarded. The syntax to call a function in VBScript is:

[call] FunctionName(argument1, argument2, etc.)

Calling a Function from an Event Handler

Functions are often called when an event occurs. Event handlers can be used to intercept an event and to cause the program to call a user-defined function. In the following EXAMPLE, the form will obtain the quantity of items purchased and a function will calculate the total cost. When the user clicks the SUBMIT button, the click event is triggered and the onClick event handler calls a function named calcTotal. The calcTotal function is a user-defined function that calculates the total cost of the user's shopping cart. Tables are used to align the form fields.

Passing an Argument to a Function

Often, we need to pass an argument to a function. This EXAMPLE, we will combine events, methods and functions to create an interactive Web page. The user changes the background color by clicking a button. The onClick event handler will call a function, and pass an argument to the function. Each event handler will call the same function, but will pass a different argument - the color chosen.

In the following EXAMPLE, the onMouseOver event handler will change the message on the status bar. We will pass an argument to a function that changes the status message. For example, when the user places the pointer over a hyperlink, a function is called, and an argument indicating what the status message should be will be passed. The function uses the argument to change the status message. The keywords return true are used to cause any changes to the status property to be reflected by the browser.

Returning a Value from a Function

The following EXAMPLE uses VBScript to create and call a user-defined function, and it demonstrates how a function can return a value to the script that called it. JavaScript functions return a value using the keyword return, and the value. VBScript functions assign the value to the function.

Using Procedures

VBScript allows us to create another kind of code block called a procedure. A procedure is similar to a function, in that it is a block of code that can be called from other locations. However, procedures do not return values, and they cannot be used in an expression. The syntax for creating a procedure is:

Sub ProcedureName(arguments)
      Action and Control Statements
End Sub

The keyword call is used to call a function or procedure, and it is optional. If the keyword call is used, the arguments passed to the procedure must be enclosed in parentheses. Multiple arguments are passed in a comma-delimited list. The syntax for calling a procedure in VBScript is as follows:

[call] ProcedureName(arguments)

We can produce more efficient code that can be reused by other scripts if we segment our code into functions and procedures. We can then call multiple procedures in the same function. One advantage of using multiple procedures is that if one of the steps changes, then only that step needs to be modified. If multiple variables are to be used across functions and procedures, they need to be global to the application and defined before the functions and procedures that reference them.

Although procedures do not return values, we can assign their values to the value property of form fields.

Check out this EXAMPLE that uses procedures to calculate the total cost of a product.

Event Procedures

In addition to the way we've used EVENT HANDLERS with onClick and onLoad, VBScript allows us to intercept events using an event procedure. An event procedure is a type of procedure that is attached to an object. Therefore, an event procedure does not return a value. When an object recognizes an event, it will immediately call the event  procedure. The event procedure provides a connection between the object and the code.

Event procedures are named according to the name of the object and the event name. An underscore(_) is used to separate the object name and the event name. For example, if you decide to create a button named btnExit to call an event procedure when the button is clicked, you would name the event procedure BtnExit_onClick. You must assign the name of the object in the HTML code before you define the event procedure. Note that the event procedure is not called, but rather, it is triggered when the event occurs for that specific object.

Check out this EXAMPLE, a modification of the previous example, which uses an event procedure to call another procedure.