USER DEFINED FUNCTION:
Functions are useful:
·
when
you have to use the same codes several times.
·
as
the JavaScript event handler.
·
make
your program easier to read and understood.
A function accepts zero or
more arguments from the caller, performs the operations defined in the body,
and returns zero or a single result to the caller.
Syntax:
function functionName(argument1, argument2, ...) {
statements;
......
return value;
......
}
Example-1:
Function
big(a,b)
{
If (a>b)
return a else return b
}
DESCRIPTION:
·
Functions are declared using the keyword
function
.
·
Need not to specify the
return-type and the types of the arguments because JavaScript is loosely typed.
·
can use a
return
statement to return a single piece of result to the caller
anywhere inside the function body.
·
If no
return
statement is used (or a return
with no value), JavaScript returns undefined
.
·
Functions are generally defined in the
HEAD
section,
so that it is always loaded before being invoked.
·
To invoke a function, use functionName
(
argument1,
argument2, ...)
.
Example-2:
<html>
<head>
<title>Function Demo</title>
<script type="text/javascript">
function add(item1, item2) { // Take two numbers or strings
return parseInt(item1) + parseInt(item2); // Simply item1 + item2 won't work for strings
}
</script>
</head>
<body>
<script type="text/javascript">
var number1 = prompt('Enter the first integer:'); // returns a string
var number2 = prompt('Enter the second integer:'); // returns a string
alert('The sum is ' + add(number1, number2));
</script>
</body>
</html>
Function has access to an additional variable called
arguments
inside its body, which is an array containing all the arguments. For example,<html>
<head>
<title>Function Demo</title>
<script type="text/javascript">
function add() {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += parseFloat(arguments[i]);
}
return sum;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(add(1, 2, 3, 4, 5) + "<br \>");
document.write(add(1, 2) + "<br \>");
document.write(add(1.1, "2.2") + "<br \>");
</script>
</body>
</html>
Primitive arguments are passed by value. That
is, a copy of the variable is made and passed into the function.
No comments:
Post a Comment