Sometimes instead of just adding your javascript to the page and having the browser perform the tasks as soon as the script is read, you might want your javascript to be performed only upon the detection of a certain event. A function is a block of code which can be called from any point in a script after it has been declared. It is basically a compartmentalized JavaScript designed to accomplish a single task. Furthermore, JavaScript written into functions will not be performed until you specifically ask for it. This way you gain complete control of the timing. Functions are useful because they contribute to rapid, reliable, error-reducing coding, and increase legibility by tiding up complicated code sequences.
A JavaScript function can take 0 or more named parameters. The function body can contain as many statements as you like, and can declare its own variables which are local to that function. The return statement can be used to return a value at any time, terminating the function. If no return statement is used (or an empty return with no value), JavaScript returns undefined.
In JavaScript a function is defined as follows:
<script type="text/javascript">
function function_name (argument_1, ... , argument_n)
{
statement_1;
statement_2;
...
statement_m;
return return_value;
}
</script>
A function definition consists of the function keyword, followed by:
- The name of the function.
- A list of arguments to the function, enclosed in parentheses and separated by commas.
- The JavaScript statements that define the function, enclosed in curly braces, { }. The statements in a function can include calls to other functions defined in the current application.
- The last statement in the statement block should be a return statement, which returns control back to whatever called the function. The keyword return can stand alone or it can be followed by a value to be returned. If no value is specified, then the function returns undefined.
Have a look at the code for a function that is used to display a message. The script will not be executed before the user hits the button. We have added an onClick event to the button that will execute the function showmessage() when the button is clicked.
<html>
<head>
<script type="text/javascript">
function showmessage() {
alert("WebCheatSheet - JavaScript Tutorial!");
}
</script>
</head>
<body>
<form name="myform">
<input type="button" value="Click me!" onclick="showmessage()">
</form>
</body>
</html>
Click the button to see what the script in the preceding example does:
Defining functions doesn`t execute it. You have to call the function for it to do its work. You can invoke (or call) any function defined in the current page. You can also invoke functions defined by other named windows or frames.
You should invoke a function by name. The name needs to be followed by a set of parentheses that contain zero or more values to be passed to the function. The number of values being passed should be equal to the number of arguments the function has. The values are assigned to the arguments in the order in which they appear in the list.
For example, if you defined the example function showmessage() in the HEAD of the document, you could call it as follows:
<script type="text/javascript">
showmessage ();
</script>
A function can even be recursive, that is, it can call itself. For example, here is a function that computes factorials:
<script type="text/javascript">
function factorial(n) {
if ((n == 0) || (n == 1))
return 1
else {
result = (n * factorial(n-1) )
return result
}
}
</script>
You could then display the factorials of one through 10 as follows:
<script type="text/javascript">
for (i = 0; i < 10; i++) {
document.write("<BR>", i, " factorial is ", factorial(i))
}
</script>
The arguments of a function are maintained in an array. This array contains a list of values of all arguments passed to the function. Within a function, you can address the parameters passed to it as follows:
function_name.arguments[number_of_the_argument]
The total number of arguments is indicated by the variable arguments.length.
Using the arguments array, you can call a function with more arguments than it is formally declared to accept using. This is often useful if you don’t know in advance how many arguments will be passed to the function. If you pass five arguments to a function only expecting three, only the first three will be assigned to the argument names defined with the function, but the other two are still addressable through the arguments object.
For example, consider a function defined to create HTML lists:
<html>
<head>
<title>WebCheatSheet - JavaScript Tutorial</title>
<script type="text/javascript">
function createList() {
document.write("<UL>") // begin list
// iterate through arguments
for (var i = 0; i < createList.arguments.length; i++)
document.write("<LI>" + createList.arguments[i])
document.write("</UL>") // end list
}
</script>
</head>
<body>
<h1>WebCheatSheet - JavaScript Tutorial</h1>
<script type="text/javascript">
createList("first","second", "third","etc");
</script>
</body>
</html>