A function is a definition of a set of deferred actions. Functions are invoked by event handlers or by statements elsewhere in the script.
Whenever possible, good functions are designed for reuse in other documents. They can become building blocks you use over and over again.
A function is capable of returning a value to the statement that invoked it, but this is not a requirement. However, when a function does return a value, the calling statement treats the function call like any expression—plugging in the returned value right where the function call is made. I will show some examples in a moment.
function functionName ( [parameter1]...[,parameterN] )
Names you assign to functions have the same restrictions as names you assign to HTML elements and variables. You should devise a name that succinctly describes what the function does.
I tend to use multiword names with the interCap (internally capitalized) format that start with a verb because functions are action items, even if they do nothing more than get or set a value.
Another practice to keep in mind as you start to create functions is to keep the focus of each function as narrow as possible. It is possible to generate functions that are literally hundreds of lines long. Such functions are usually difficult to maintain and debug.
Chances are that you can divide the long function into smaller, more tightly focused segments.
You also can define functions so they receive parameter values from the calling statement.
alert(“The button sent: “ + msg);
<input type=”button” value=”Click Me”
onclick=”showMsg(‘Welcome To Visions Developer!’)”>
Above Example shows a simple document that has a button whose onclick event handler calls a function while passing text data to the function. The text string in the event handler call is in a nested string—a set of single quotes inside the double quotes required for the entire event handler attribute.
Parameters (also known as arguments) provide a mechanism for “handing off” a value from one statement to another by way of a function call. If no parameters occur in the function definition, both the function definition and call to the function have only empty sets of parentheses.
When a function receives parameters, it assigns the incoming values to the variable names specified in the function definition’s parentheses.