![]() | MSc-IT Study Material June 2010 Edition Computer Science Department, University of Cape Town |
Table of Contents
JavaScript functions are usually given a name, but since JavaScript functions are just objects in their own right, they can be stored in variables and object properties (see later unit). Functions are different from other objects in that they can be invoked (executed) with the use of a special operator ().
JavaScript provides many pre-written (built-it) functions, for example the function write, provided by the document object (see in a later unit how related functions can be stored inside objects; as we noted a few units ago, such functions are called methods).
An example of the write function being invoked is as follows:
document.write( "This message appears in the HTML document" );
The browser output for this code is:
An example of the alert function being invoked is as follows:
alert( "This message appears in an alert dialog" );
The browser output for this code is:
Some functions return a value. For example, mathematical functions perform calculations on the provided data and return numerical results. Other functions return true/false values, or text. Some functions return no value at all, but rather perform a side-effect; write is one such function whose side-effect is to send text to the HTML document. Functions frequently both perform a side-effect and return a value.
Functions can be used for many different purposes. In the past, JavaScript was used to create scrolling status bar messages for sites that want to give out important information that the user may miss while browsing the site (these proved to be largely irritating to the user, and have been very rarely used in the last few years). Displaying the date and time is also a common use of JavaScript. Image mouseovers, implemented using the HTML event system described in the previous chapter, are also widely used.
Functions are very useful when used in conjunction with HTML forms. Form entry can be validated, and the input of early parts of the forms might be used to invoke functions to automatically enter appropriate data in other parts of the forms.
Read up about JavaScripts Functions in your textbook.