JavaScript User-Defined Functions
JavaScript
User-Defined Functions
A user-defined
function saves us from rewriting the same code again and again and helps
us to make our application smaller. The given examples will help you to
understand how you can put them to work.
JavaScript has so many
built-in functions, besides that you can make your own as per the need. General
structure of the user defined function is:
function
function_name(par1, par2, …)
{
//statements
}
par1, par2 are the
name of the parameter, one function could have one, more than one or no
parameter. Parameters could be of any data type.
Example 1(Simple
Function):
<html>
<head>
<title>Simple Function</title>
<script type="text/javascript" >
function
display()
{
document.write("Welcome
to Java Script!!!");
}
display();
</script>
</head>
</html>
Output:
Welcome to Java
Script!!!
Example 2 (Return a
Value):
<html>
<head>
<title>Return Value Function</title>
<script type="text/javascript" >
function add(x, y)
{
return (x+y);
}
</script>
</head>
<body>
<script type="text/javascript">
var x=add(20,35);
document.write("Addition is " + x);
</script>
</body>
</html>
Output:
Addition is 55
Example 3 (Return a
String):
<html>
<head>
<title>Return String Function</title>
<script type="text/javascript" >
function display()
{
return("Return
String Statement");
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(display());
</script>
</body>
</html>
Output:
Return String Statement
Comments
Post a Comment