Function in JavaScript
- What Is A Function ?
-
Ajavascript function is a collection of statements either named or unnamed that can be called from elsewhere in a JavaScript program.
-
A function will be executed by an event or an explicit call to the function.
-
Functions can be defined in both <head> and <body> section but generally are placed in the head section.
Sayntax
<script type=“text/javascript”>
function <function name>(arg 1,arg 2. . .)
{
// some code
}
</script>
Calling a Function
<script type=“text/javascript”>
<function name>(arg 1,arg 2. . .);
</script>
function <function name>(var 1,var 2. . .)
{
// some code
}
Point To Remember
-
A function with no parameters must include a parenthesis after it’s name
-
The word “function” must be written in lowercase.
Using Argument Array
-
Whenever a function is invoked it gets an object called “arguments” which acts like an array and holds the arguments sent to a function.
-
This feature is very helpful if we don’t know how many arguments might be passed to the function.
PROGRAM
Write a JavaScript function called “average( )” which should accept some integers as arguments and calculates and displays their sum and average.
Calling Functions From Link
A function can be called directly from a link by using JavaScript pseudoprotocol called “JavaScript:” .
Syntax
<a href=“JavaScript:<functionname>( );”>some text </a>