Functions

Functions are useful for a number of reasons. Functions are containers for script that is only to be executed by an event or a call to the function. Therefore, functions do not execute when the browser initially loads and executes the script that is included in a web page. The purpose of a function is to contain script that has a task so that you then have the ability to execute that script and run that task at any time.

Structuring a function is easy; it begins with the word function followed by a space and then the name of the function. The name of the function can be anything you choose; however, it is important to make it something that relates to the task it performs. Below shows an example of a function that changes the value of an existing variable.

Structuring a simple function

var num = 10;

function changeVariableValue(){

num = 11;

}

changeVariableValue();

document.write("num is: "+ num);

The example above not only shows how to structure a function, it also shows how to call a function and change the value of a variable. You can change the variable value in this case because the variable is declared within the scope of the main script, as is the function, so the function is aware of the variable. However, if the variable is declared within the function you cannot access it outside of the function.

Functions also have the ability to accept data through function parameters. Functions can have one or more parameters, and a function call can have one or more arguments based on the number of function parameters. It is common to confuse parameters and arguments; parameters are part of the function definition, and arguments are expressions used when calling the function. Below shows an example of a function that has parameters and a function call with arguments.

Using function parameters

var num = 10;

function increase(val){

val++;

}

increase(num);

document.write("num is: "+ num);

The function in this example increases the value of any argument passed to it. The argument in this case is a variable that you have already declared. By passing it as an argument to the function you are increasing its value to 11.

Return statements are also commonly used in functions. They return a value after executing the script in a function. For example, you can assign the value that is returned by a function to a variable. Below shows an example of how to return a value from a function after executing the script.

Using the return statement in a function

var num = 10;

function add(val1, val2)

{

return val1+val2;

}

var sum = add(10, 20);

document.write("Sum is: "+ sum);