Javascript Function

A Javascript function is a named procedure that performs a distinct service. A function is a small reusable subset of program that can be defined anywhere in the code and composed with set of statements. Like other languages javascript function allow to pass value to a function, and the function can return a value.

To return a specific value other than the default value, a function must have a "return" statement that specifies the value to return. In JavaScript, functions are objects, and can be manipulated and passed anywhere just like any other object. The defference between function and procedures, a function always returns a value, but a procedure may or may not return any value. Function Declarations must begin with "function" keyword. A Javascript function hase the following general form:

Syntax

<script type="text/javascript">
function <function name> (argument list.....){
Statements .....
}
</script>

The arguments list is list of variables names. In javascript variable types is not defined in the function. Also return type is not defined for function.

Javascript Function without Parameter Example

<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>Example of function without parameter</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function showMessage()
{
   alert('Hello Javascript');
}
</SCRIPT>
</HEAD>
<BODY>
<H3>Example of function call</H3>
<form name="myform">
<INPUT TYPE="button" VALUE="Show Message" onClick="showMessage();">
</form>
</BODY>
</HTML>

Sometimes we pass parameters or arguments to functions, these parameters will be used inside the function for required calculations. For an example we will use two numbers to add using function.

Javascript Function with Parameters Example

<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>Example of function parameter with return value</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function add(a, b)
{
var c;
return a + b;
}

add(120, 40);
</SCRIPT>

</HEAD>
<BODY>
<H3>Example of function return value</H3>
</BODY>
</HTML>