|
Functions
A function contains some code that will be executed by an event
or a call to that function. A function is a set of statements.
You can reuse functions within the same script, or in other
documents. You define functions at the beginning of a file (in
the head section), and call them later in the document. It is
now time to take a lesson about the alert-box:
This is JavaScript's method to alert the user.
alert("here goes the message")
How to define a function
To create a function you define its name, any values
("arguments"), and some statements:
function myfunction(argument1,argument2,etc) { some
statements }
A function with no arguments must include the brackets:
function myfunction() { some statements }
Arguments are variables that will be used in the function. The
variable values will be the values passed on by the function
call.
By placing functions in the head section of the document, you
make sure that all the code in the function has been loaded
before the function is called.
Some functions returns a value to the calling expression
function result(a,b) { c=a+b return c }
How to call a function
A function is not executed before it is called.
You can call a function containing arguments:
myfunction(argument1,argument2,etc)
or without arguments:
myfunction()
The return statement
Functions that will return a result, must use the return
statement, this statement specifies the value which will be
returned to where the function was called from. Say you have a
function that returns the sum of two numbers:
function total(a,b) { result=a+b return result }
When you call this function you must send two arguments with it:
sum=total(2,3)
The variable sum has the value 5.
Examples
1. How to call a function
Coding
<html>
<head>
<script language="JavaScript">
function myfunction()
{
alert("HELLO")
}
</script>
</head>
<body>
<form>
<input type="button"
onclick="myfunction()"
value="Call function">
</form>
</body>
</html>
2. How to pass variable values from a call to a function, and
use these values in the function
Coding
<html>
<head>
<script language="JavaScript">
function myfunction(txt)
{
alert(txt)
}
</script>
</head>
<body>
<form>
<input type="button"
onclick="myfunction('Hello')"
value="Call function">
</form>
</body>
</html>
3. How to let the function return a value
Coding
<html>
<head>
<script language="JavaScript">
function total(a,b)
{
result=a+b
return result
}
</script>
</head>
<body>
<script language="JavaScript">
sum=total(2,3)
document.write(sum)
</script>
</body>
</html>
Output
5
|