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 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.
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:
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:
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: