So, functions allow the programmer to divide up scripts into groups of instructions which can be run in response to user events or used to create areas of code which scripts would need to access repetitively.
Functions are implemented as follows:
The following code defines a function which works out how much VAT is charged on any given price. It formats this value nicely (to 2 decimal places) and then returns it to the line of code which called it.
This technique can save a lot of time if the same code needs to be used multiple times, for example, if you have VAT to calculate on a number of prices rather than just one. In this instance the code would only need to be extended so that other lines of code also call the function.
// Get VAT paid on a price of £10.99 var amountOfVAT = getVAT(10.99); // Get VAT paid on a price of £2.99 var anotherAmountOfVAT = getVAT(2.99); // Get VAT paid on a price of £7.99 var aFinalAmountOfVAT = getVAT(7.99);
In the above example, the same function is called 3 times and returns 3 different results into the 3 variables declared without having to repeat the lines of code which make the calculation.
This next block of code uses a function to help write data into a HTML table. The use of the function in this example helps keep the logical code (where the data is) apart from the display code (the bit that draws the table HTML).
The code in this example passes three items of data into the function rather than just one. Note that the items of data are seperated with commas in both the call to the function and in the function definition. Also notice that information can "returned" from the function to the script which called it. This can be assigned to variables in the usual way.
For more on functions read W3Schools functions page.
Now open the functions exercise page and work through it.