Functions

|

A function contains code that will be executed by an event or by a call to that function. You can however use a function to contain the script and call it every time your need it. Here is the syntax for a function.

Syntax:
function name (parameters){
statements
}

The function keyword identifies this as a function. The parameters in the parenthesis ( ) provide a means of passing values to the function. There can be as many parameters separated by commas as you need. It is perfectly ok to have a function with no parameters. These parameters are variables which are used by the JavaScript statements inside the curly braces { }. The var keyword is not needed to declare the parameters in a function as variables because they are automatically declared and initialized when the function is called. The function can return a value by using the return keyword.

You should put your functions in the HEAD section of your document. Functions will work if you put them in the BODY section. However, a function must be loaded prior to the statement that calls it. Putting all functions in the HEAD section is the way to insute this.

Example:
function myAdder (num1, num2){
var total = num1 + num2
document.write(total)
}

You would place this function inside some <SCRIPT> tags in the head section. You then can call the function from anywhere in your document. In this example, lets call it from within some <SCRIPT> tags in the body of document like this.

myAdder(23, 56)

Scope of Variables
A variable that is defined outside of a function is a global variable. A variable that is defined inside of a function is a local variable. What does this mean? Global variables can be used anywhere in the document that is currently loaded in the browser. They can be declared in the HEAD section and used in any function or even in the BODY section. Local variables can only be used in the function that declares them. Yes, you could leave the var keyword off of the variables you declare inside of a function and they will then be global. I do not recommend this.




 

©2009