Functions
Functions are similar to methods but are not adjoined to a given base object. They offer the ability for programmers to group together many lines of code, or code blocks, to perform specific tasks so that they can be used repeatedly throughout the program. JavaScript already has some built-in functions, such as eval() , parseInt() , and parseFloat() , that you may already be familiar with. In many cases, however, programmers need to also define their own functions to supplement the built-in JavaScript functions. JavaScript offers this capability and flexibility.
Defining Functions
A function is declared by name and is invoked by calling its name in code. It is used in a block statement by using the reserved word function :
function functionname (parameter, arguments) { command block }
Function-naming conventions follow the same rules as variables :
- Are case sensitive
- Can include underscores
- Must begin with a letter
The list of arguments passed to a function is separated by a comma and is always enclosed in parentheses. To execute a function, it must be called. Just defining it does not mean that it will be executed.
Parameters
Parameters are used to pass data into a function and are used to return data from a function. Some functions return a value, whereas others just perform a task. In the following example, the statusbar() function uses the message parameter to pass data into the function:
function statusbar(message) { window.status = message; return true; } function statusbaroff() { window.status = ""; return true; }
The function is then called in the onFocus event of a field on a form:
statusbar("Enter the company name for this customer.");
When a user places the cursor in a field, the message is passed as the argument and is then displayed on the user 's status bar. Figure 16.15 shows how the code looks from inside the JS Header :
Figure 16.15. The statusbar function inside the JS Header event.
Figure 16.16 shows the JavaScript calling the function in the onFocus event of a field.
Figure 16.16. The statusbar function inside a field's onFocus event.
Another way to pass arguments to a function is to set a global variable:
var favcolor = prompt("What is your favorite color?", "Blue"); function printcolor(favcolor) { document.write("
Your favorite color is "); document.write(favcolor); document.write("/B>
"); }
Here's how to call the function in an event:
printcolor(favcolor)
Using Multiple Parameters
Functions can pass multiple arguments as well. The only stipulation is that you must call or use them in the same order as they are defined in the function. For example:
Function winelist(selection, year) { If (selection == "Chardonnay" && year=="1985"){ return true; }Else{ return false; } }
You can call a multiparameter function in several ways. Here are some examples:
//declaring a variable var wines = winelist("Red", "1996"); //Using the if... statement if ( winelist("Red", "1996") ){ ... other code here } //Using the onLoad event onLoad = "winelist(selection, year)";
When more than one function parameter is being used, be careful of the order in which the parameters are defined. When one parameter is a string and the other is a number, and they are called in the reverse order, the result is an error when the code is compiled. This example shows the incorrect way to call a multiparameter function:
var selection = prompt("What type of wine would you like with dinner?", "Chardonnay"); var numbottles = 1; winelist(numbottles, selection); function winelist(selection, numbottles){ If (selection == "Chardonnay"){ return true; }else{ Prompt("Sorry we only have Chardonnay in stock!"); return false; } }
This calls the function incorrectly:
winelist(numbottles,selection)
This results in an error at runtime.
Returning the Results
To return a value of a function's result, a return statement must be used in the code block:
function winelist(selection) { If (selection == "Chardonnay"){ return true; }else{ return false; } }
In this case, if the wine list selection equals "Chardonnay" , true is returned by the function.
Built-In Functions
Sometimes using the built-in functions make more sense than creating your own functions. Why reinvent the wheel? Eval() is a good example of a JavaScript built-in function that you should not have to re-create.
Eval()
Eval() evaluates a string to a numeric value. This expression might be any string, variable, property of an existing object, or statement. Here's an example:
var gBeans = 0; function countJellyBeans(jar1, jar2, jar3){ gBeans = eval("jar1+jar2+jar3"); }
In this example, eval() is used to sum the total of jellybeans in each jar.
ParseInt()
ParseInt() evaluates a string argument and returns an integer. The integer returned depends on its base (decimal, octal, or hexadecimal). Here's an example:
var jar1 = "326.25"; gBeans = 0; Function countJellyBeans(jar1){ gBeans = parseInt(jar1); }
In this example, the integer 326 would be returned as the total number of jellybeans in jar1 .
ParseFloat()
ParseFloat() evaluates a string argument and returns a floating-point number. Here's an example:
var jar1 = "+326.25987098+2"; gBeans = 0; Function countJellyBeans(jar1){ gBeans = parseInt(jar1); }
In this example, the number 326.25987098 would be returned as the total number of jellybeans in jar1 .