JavaScript Functions
Written
Author
FUNCTIONS are small groups of instructions that are carried out when they are called upon. They are usually placed in the HEAD area of the page code. If you have a page that will be doing the same task many times, it's best to use a function to organize them.
A very basic example of how to use a function:
FUNCTION tells the browser "Do these instructions when this name is called upon.".
SomeName( ) sets a name to this set of instructions. SomeName is what I used for my function example. You can call it whatever you like. The round brackets are used to symbolize a function parameter. In this case, it is left blank. In the main BODY area, the function is simply called by the name.
The curly brackets are used to contain the set of instructions.
Both functions and the calling of functions are placed within the SCRIPT tags. They are both part of JavaScript and you have to let the code know that.
Each time the SomeName( ) function is called in the BODY area, the browser will look for that function and carry out that set of instructions.
Function Parameters
Parameters allow you to pass information into the function instead of simply carrying out a given set of instructions.
Here is an example showing a function being called upon 3 times with different parameter values assigned each time. Functions can be used over and over again.
Each time the function is "called" from the BODY area, the browser looks for that function and carries out it's set of instructions.
When the function FindTotal is called, the 3 values will be sent to the function area and get placed into temporary storage areas. For this example : first, next, last are being used.
A new temporary storage area, called total, will be created to do the calculations. This step is not really necessary, but it helps to keep the coding more organized.
The document.write then prints out the value stored in total plus some text.
The result from this example should be : Your total is 9. Your total is 14. Your total is 16.
Using function parameters are not limited to just coded in numbers. Input can be obtained from the visitor to be used. This example will ask the visitor for their name and age. It then calculates the age into seconds and prints out a message.
In the BODY area, the function is called upon which activates the x and y variables. These two variables are the prompt pop-up boxes and store the input information. That information is then passed into the temporary storage areas called first and next to do the calculations and other function commands.
Table of Contents
Table of Contents