Functions are one of the fundamental building blocks in JavaScript.
A function is a JavaScript procedure -- a set of statements that performs
a specific task. A function definition has these basic parts:
The statements in the function in curly braces: { }
Defining a Function
When defining a function, it is very important that you pay close attention to the syntax.
Unlike HTML, JavaScript is case sensitive, and it is very important to remember to enclose
a function within curly braces { }, separate parameters with commas, and use a semi-colon
at the end of your line of code.
Defining the function names and inside the function specifies what to do when the
function is called. You can define a function within the
<SCRIPT>...</SCRIPT> tags within the <HEAD>...</HEAD>
tags. In defining a function, you must declare the variables which you will
be calling in that function.
Calling a Function
Calling the function actually performs the specified actions. When you call a function,
this is usually within the BODY of the HTML page, and you usually pass a parameter into
the function. A parameter is a variable from outside of the defined function on which
the function will act.
Example:
<html>
<head>
<script type="text/javascript">
<!--
function HelloWorld() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="HelloWorld()" value="Click Me" />
</body>
</html>
A function with one parameter.
lt;html>
<head>
<script type="text/javascript">
<!--
function Hello(name) {
alert("Hello " + name);
}
//-->
</script>
</head>
<body>
<input type="button" onclick="Hello('Friend')" value="Click Me" />
</body>
</html>