Functions

Functions help organize the various parts of a script into different tasks that must be accomplished.
A function contains code that will be executed by an event or by a call to the function.
Functions can be used more than once within a script to perform their task. Rather than rewriting the entire block of code, you can simply call the function again.

There are two kinds of functions:

1. Declaring Functions

Functions can be defined both in the <head> and in the <body> section of a document. However, to assure that a function is read/loaded by the browser before it is called, it's better to put functions in the <head> section.
The most basic way to define a function is using the word "function", the name of the function followed by two parentheses (where we can add the parameters) and a pair of cfurly brackets that contain the code of the function.

Function syntax
function functionName(var1, var2, ...) {
  code to be executed
}
The parameters var1, var2, etc. are variables or values passed into the function. The brackets { and the } defines the start and end of the function.
- A function with no parameters must include the parentheses () after the function name.

Function names are case sensitive, be sure you use the identical name when you call the function.
The word function must be written in lowercase letters.

2. The Return Statement

A return statement is used to specific a value that a function returns to the main script. You place the return statement as the last line of the function before the closing curly bracket and end it with a semicolon.
For example, to return the value of a variable "some_var", the return statement looks like this:
                return some_var; The next function returns the value of a variable 'z' that contain the amount of two parameers (x, y):
function amount(x, y) {
  var z = x+y;
  return z;
}
- The "amount" is the name of the function, "x" and "y" are the parametres. The function returns the value of "z" variable, that contain the amount of "x" and "y".

3. Calling Functions

After the function is defined, we can call and use it.
You may call a function from anywhere within a page (or even from other pages if the function is embedded in an external .js file). You can even call a function inside of another function.
A function with parameters can be called using the syntax:
functionName(arg1, arg2, ...);
- "arg1", "arg2", ... are the arguments passed to the function.
A function without paramentre with the following syntax:
functionName();
Note that the function call no longer use the word "function" and braces
In the place of the script where we call a function it's executed the code of that function.

4. Sample scripts with functions

- Example 1 - function without parameter
The JS script of the next example display a text in the web page:
<html>
<head>
<script type="text/javascript"><!--
function ex1() {
  return document.write("Welcome!");
}
--></script>
</head>
<body>
<script type="text/javascript">
ex1();
</script>
</body>
</html>
- The function "ex1" was defined in the Head section of the HTML document and then was called in the "Body", where will display the text "Welcome!".

- Example 2 - function with one parameter
The script in the next example opens an Alert window with a text received as an argument of a function.
<html>
<head>
<script type="text/javascript"><!--
function ex2(text) {
  alert(text);
}
--></script>
</head>
<body>
<form>
 <input type="button" onclick="ex2('Good morning!')" value="Morning" />
 <input type="button" onclick="ex2('Good afternoon!')" value="Afternoon" />
</form> </body> </html>
- This code will return the following effect. Just click the buttons.:
- The text displayed in the Alert pop-up is taken from the argument passed to the function when the function is called.
- "onclick" (la click) is a JavaScript method that specifying the time when the function will be executed.

- Example 3 - function with two parameters
The function in this example opens an Alert pop-up that will display the result of the multiplication of two numbers.
<html>
<head>
<script type="text/javascript"><!--
function ex3(x,y) { 
  var z = x*y;
  return alert(x+" * "+y+" = "+z)
}
--></script>
</head>
<body>
<form>
 <input type="button" onclick="ex3(7, 8)" value="7*8" />
</form>
</body>
</html>
- This code will display the next results:
- When you click the button an alert window will display the result of the 7*8.

Inside the function can be used complex instructions: "for", "if", "while", which may take different decisions depending on the function arguments. It only depends on your knowledge and imagination


• Another way to declare a function is to use the function literal form as a value of a variable.
Syntax
var variable_name = function(var1, var2, ...) {
  code to be executed
}
- "var1", "var2" are the parameter of the function.
This is also known as an anonymous function. The term "anonymous" refers to the fact that it does not necessarily have a name.
When we call this function we use the variable name like the name of the function, as you can see in the fallowing example:
<script type="text/javascript"><!--
// Declaring a function using the function literal notation (an "anonymous" function)
var write_msg = function(msg) {
  // First we check if the argument exists
  if(msg)
    document.write(msg);
  }
// Print a message
write_msg("Welcome!");       // Welcome!
--></script>
- This script will display the message "Welcome!".

The last way to declare a function is to use the Function object constructor. The Function class has a constructor that uses the following unusual syntax:
functionName = new Function( "param1, param2,...paramX", functionBody );
- The parameter names and the "functionBody" must be written as strings.
- This will work like other functions, but the main drawback to this method is that it has poorer performance than the other methods (it is evaluated every time it is used rather than only being parsed once).
- If you were to rewrite the "write_msg()" function with this approach, it would look like this:
<script type="text/javascript"><!--
// Declaring a function using the Function class constructor
var write_msg = new Function("msg", "if (msg) document.write(msg);");
write_msg("Welcome!");         // "Welcome!"
--></script>