Techcss
Javascript_page_menu

JavaScript Functions

A function is a perticular task performing routine or program that groups a number of program statements into units which are named and invoked from other parts of the program.

If we do program in a generic, object based approach to the script, the function can be made portable in such a way that we can reuse it in other scripts or keep it in the online server (public network) to share it with the developers community.


Defining Functions

A simple structure of function is:

function col_sum(arguments) {
// code goes here //
..........
.......... }

If a function is defined in a program, it does not imply that the codes in code block in finction are executed. The code block is executed only when the function is called by name elsewhere in script or program.


Passing Parameters

When we call a function we can pass both variables and literals as arguments.

Parameters exixts only for the duration of each time a function is called parameters are created fresh.
Example:
<html>
<head>
<script> function square(num){ var sqr;
sqr = num * num; return sqr; } </script> </head>
<body> <script> var input = prompt("Enter a number","1"); var output = square(input);
document.write("The square of " + input + "is = " + output);
</script> </body>
</html>

The use of Variables in functions

We can use two types of variables in JavaScript, i.e, local variables and global variables.

A variable defined using the var command withina function will have limited scope to that function only. So they are referred to as local variables.

If a variable is declared outside the body of function, the variable is available throughout the script, even inside other functions. Hence they are referred to as global variables.

If a local variable and global variable are having same name within the corresponding function the variable name refers to the local variable and not as global variable.

Where to place (define) a function in an html document?

This is compulsory to put the function definitions within the <head></head> tags of an html document. This ensures parsing of all functions before user events can invoke them to prevent the display from any error messages. Parsing involves processing each line of script code and converting it to a pseudo-compiled Byte-Code. Syntax errors also screened during parsing and can be rectified immediately.


Recursive Functions

The functions call themselves to fulfill the output requirement are called as Recursive Functions.

<script>
function factorial(num)
{
if(num > 1){ return num * factorial(num-1); } else { return num; } }
</script>

A recursive function calls itself repeatedly till a condition is met.