A function is a reusable code-block that will be executed by an event, or when the function is called. A function contains code that will be executed by an event or by a call to the function. You may call a function from anywhere within a page.

How to Define a Function

To create a function you define its name, any values (argument), and some statements.

Syntax

function  functionname(var1,var2,...,var n)
{
statements
}

Example

<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Welcome to REC Dang");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me" onclick="displaymessage()">
</form>
</body>
</html>

The return Statement:

The return statement is used to specify the value that is returned from the function. So, functions that are going to return a value must use the return statement.

Example:

Function total(a,b)
{
      Result=a+b
      Return result
}

When you call this function you must sent two arguments with it.
       total(3,5)

 Example

<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>
</body>
</html>

WAP to find factorial using function.

<html>
<head>
<script type="text/javascript">
function factorial(a)
{
var fact=1,i;
for(i=1;i<=a;i++)
{
       fact=fact*i;
}
return fact;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(factorial(4));
</script>
</body>
</html>

Function in Java script

The Java script functions can be classified into two categories: built in and user defined function.

1.Built in functions

These are the functions which are predefined and placed in library and they are not required to be written by a programmer.

Example:

Length( ) function can be used to find the length of a string.
i.e.
var txt="Hello world";
document.write(txt.length);

2.User defined functions:

These are the functions which are defined by the user and called when needed.

Example

<html>
<head>
<script type="text/javascript">
function area(l,b)
{
var l,b,a;
a=l*b;
return a;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write("Area :"+area(5,3));
</script>
</body>
</html>