Function
What is Function?

Function is just like container for script. In Function we write script. When we call function then store script will run. Once you have to create function. You can call this function anywhere in Programme. If We not use function then we write script again and again. Function has generally two type:

Library Function:- This is done by Javascript Object.We just call it.
User Define Function:- This is Just created by Programmer. Means Programmer self create function then call it.

User Define Function.

This is create by Programmer. Means Programmer self write script into function.

Syntax for Create user define function

function functionname()
{
write code here;
}

Syntax to Call user define function

functionname(argument); 

Example 1:- Example to Create Function and Call function

<html>
<head>
<title>My JavaScript Programme</title>
</head>
<body>
<script language="javascript" language="javascript">
function show()
{
document.write('Welcome User');
}
show();
</script>
</body>
</html>

Output:-
Welcome User

Example 2:- How to call function onclick() event.
<html>
<head>
<title>My JavaScript Programme</title>
<script language="javascript" language="javascript">
function show()
{
document.write('welcome');
}
</script>
</head>
<body>
<input name="btn" type="button" value="Click Here" onClick="show()">
</body>
</html>

Ouput:-
Welcome
Example 3:- Add of two value using form

<html>
<head>
<title>My JavaScript Programme</title>
<script language="javascript">
function add()
{
var num1=Number(document.frm.num1.value);
var num2=Number(document.frm.num2.value);
var num3;
num3=num1+num2;
alert(num3);
}
</script>
</head>
<body>
<form name="frm" action="" onSubmit="add();">
Enter Num 1<input name="num1" type="text"><br>
Enter Num 2<input name="num2" type="text"><br>
<input name="btn" type="submit" value="Add">
</form>
</body>
</html>

Output
adding of two number that is input by user and show on alert window.

Example 4:- Passing value into function and return value from function.

<html>
<head>
<title>My JavaScript Programme</title>
<script language="javascript">
function add(x,y)
{
return x+y;
}
</script>
</head>
<body>
<script language="javascript">
document.write(add(14,6));
</script>
</body>
</html>

Output:-
20


Previous
Next