Well, functions are used to keep things more organized and readable. A function is a set of JavaScript statements put together for a single purpose. A function contains code that will be executed by an event or by a call to that function. Functions can be defined both in the <head> and in the <body> section of a document.
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<input type="button" value="Click me!" onclick="displaymessage()" >
</body>
</html>
The result is:
If the line: alert("Hello world!!") in the example above had not been put within a function, it would have been executed as soon as the line was loaded. Now, the script is not executed before the user hits the button. We have added an onClick event to the button that will execute the function displaymessage() when the button is clicked.
The syntax for creating a function is:
<SCRIPT language="JavaScript">
<!--hide from old browsers
function name (parameter1, parameter2)
{
JavaScript Statements and declarations
}
//-->
</SCRIPT>