CH-24 - JAVASCRIPT - FUNCTIONS.
What is a function?
A function is a group of reusable code which can be called anywhere in your program. This eliminates
the need of writing the same code again and again. It helps programmers in writing modular codes.
Functions allow a programmer to divide a big program into several small and manageable functions.
The basic syntax is shown here.
<script type = "text/javascript">
function functionname(parameter-List)
statements
</script>
Example:
<script type = "text/javascript" >
function sayHello() {
alert("Hello there");
</script>
Calling a Function
To invoke a function somewhere later in the script, we would simply need to write the name of that
function as shown in the following code.
<html>
<head>
<script type = "text/javascript">
function sayHello() {
[Link] ("Hello there!");
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
</body>
</html>
Function
Parameters
There is a facility to pass different parameters while calling a function. These passed parameters
can be captured inside the function and any manipulation can be done over those parameters.
<script type = "text/javascript" >
function functionname(parameter1, parameter2)
statements
}
</script>
Here's an example:
<script type = "text/javascript" >
function add(int a, int b)
alert(Hello there");
</script>
The return Statement in function
A JavaScript function can have an optional return statement. This is required if you want to return
a value from a function.
<script type = "text/javascript">
function add(int a, int b) {
ans =a +b;
return(ans);
</script>