Functions
Functions are named blocks of code that can be executed by an event or by a call to the function.
Functions may be called from anywhere within a page or even from other pages when the function is embedded in an external .js file.
Functions can be defined both in the <head>
and in the <body>
section of a document. However, to assure that a function is read/loaded by the browser before it is called, it is recommended to put functions in the <head>
section.
Defining a Function
The function
statement has the following syntax:
function funcname(var1,...,varX)
{
some code
}
The parameters, var1, etc., are variables or values passed to the function. A function with no parameters still must include the parenthesis after the function name.
The following example shows the basic use of the function
statement.
<html>
<head>
<script>
function sayhello()
{
alert("Hello JavaScript!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Say Hello" onclick="sayhello()" />
</form>
</body>
</html>
return statement
The return
statement is used to specify the value that is returned from the function.
The following example shows the basic use of the return
statement.
<html>
<head>
<script>
function sum(a,b)
{
return a+b;
}
</script>
</head>
<body>
<script>
document.write(sum(5,9));
</script>
</body>
</html>
This produces the following result:
14
Function Variable Lifetime
When a variable is declared within a function, that variable is known as a "local variable" and can only be accessed within that function. Also, these variables only exist while the function is being executed. Once the function exits, the variable is destroyed.