Functions

Videos

Examples from Videos

Notes

Functions

A function groups together a set of statements under a name. This allows you to conveniently "call" the function whenever its action is required. Functions are a fundamental building block of most JavaScript programs, so you'll become quite familiar with their use. Before you can call on a function, of course, you must first create it. We can break down the use of functions, then, into two logical categories: defining functions and calling functions.

Defining functions

The function definition is a statement which describes the function: its name, any values (known as "arguments") which it accepts incoming, and the statements of which the function is comprised.

function funcName(argument1,argument2,etc)
{ statements; }

A function doesn't necessarily require arguments, in which case you need only write out the parenthesis; e.g. funcName(). If you do specify arguments, those arguments will be variables within the function body (the statements which make up the function). The initial values of those variables will be any values passed on by the function call.

Generally it's best to define the functions for a page in the HEAD portion of a document. Since the HEAD is loaded first, this guarantees that functions are loaded before the user has a chance to do anything that might call a function. Alternately, some programmers place all of their functions into a separate file, and include them in a page using the SRC attribute of the SCRIPT tag. Either way, the key is to load the function definitions before any code is executed.

Consider, for example, a simple function which outputs an argument to the Web page, as a big, bold message:

function bigbold(message)
{ document.write("<h1>"+message+"</h1>"); }

Some functions may return a value to the calling expression. The following function accepts two arguments, x and y, and returns the result of x raised to the y power (don't worry - we'll talk about these loops in the next lecture):

function raiseP(x,y)
{ total=1;
  for (j=0; j<y; j++)
   { total=total * x; }
  return total; //result of x raised to y power
}

Calling functions

A function waits in the wings until it is called. You call a function simply by specifying its name followed by a parenthetical list of arguments, if any:

clearPage();
bigbold("Hello World!");

Functions which return a result should be called from within an expression:

total=raiseP(2,8);
if (raiseP(tax,2)<100) ...

Quite commonly, JavaScript functions are called from within event handlers (like onClick).

Where does it Go?

Functions are often in the head section of the HTML document. To do this, we use the script tag. For example, imagine a form checker that requires a value to be over 10,000 but less than 99,9999. We can put the if-else statements in a function in the head like this:

<html>
<head>
<script language=javascript>

function checker() {
        if (document.frm3.field1.value < 10000) {
                alert('your value is too small');
                return false;
        } 
        else {
                if (document.frm3.field1.value > 99999) {
                        alert('your value is too big'); 
                        return false;
                }
        }
}

</script>
</head>


and then in the form, our code looks much nicer:
<form name=frm3 method=post action=form.cgi>

<input type=text value=100000 name=field1>
<input type=submit onClick="checker()">

</form>
The form will work the same. If there is an invalid entry in the form, our function will still return false to stop the form from being submtited. Otherwise, the function doesn't return a value and the form proceeds as normal. Using functions in the header of the document combined with the document object model, we are capable of writing elegant, easy to read code.

More on Return Statements

- One common return statement we see is "return false". We use this at the end of some button clicks to keep anything from happening. For example, if we have a form and we want to check the zip code, we can check it when the user clicks the submit button. If the value is wrong, want to stop the form from being submitted. To do that, we need to say "return false" to keep the form from continuing. For example, this form does not have a return false statement:
The code looks like this:
<FORM name=frm2 method=post action="http://zaphod.cs.umd.edu/cgi-bin/reflector.cgi ">
<input type=text value=100000 name=field1>
<input type=submit 
onClick="if (document.frm2.field1.value < 10000) {
                        alert('your value is too small');
                } 
                else {
                        if (document.frm2.field1.value > 99999) {
                                alert('your value is too big'); 
                        }
                }">

</FORM>

However, this code does have the return false statement:

The code looks like this:

<FORM name=frm3 method=post action="http://zaphod.cs.umd.edu/cgi-bin/reflector.cgi">
<input type=text value=100000 name=field1>
<input type=submit 
onClick="if (document.frm3.field1.value < 10000) {
                        alert('your value is too small');
                        return false;
                } 
                else {
                        if (document.frm3.field1.value > 99999) {
                                alert('your value is too big'); 
                                return false;
                        }
                }">

</FORM>

Notice that the return false; statement is INSIDE the curly braces for the if and else statements. If we were to leave it outside of the braces, we would return false in any condition. That would keep the form from being submitted even if the value was ok. Try different values to see the difference.