Functions

A function is a set of JavaScript statements that perform a certain task. Every function must be given a name, and can be invoked (or called) by other parts of the script.

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:

function myFunctionName() {
	// JavaScript instructions here
}

Functions used for specific tasks

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.

<script type="text/javascript" language="javascript">

// declare a function, accept 1 argument "price"
function getVAT(price) {
// create a variable for VAT rate 
// this variable is only usable inside this function.
    var VATrate = 0.20;
    
// multiply the VAT rate varible with the price
// supplied as an argument, assign this to a new 
// variable called VAT
    var VAT = price * VATrate;
    
// use toFixed() to round to 2 decimal places
    VAT = VAT.toFixed(2);

// return the VAT variable from the function
    return VAT;
}

// get the amount of VAT on a price of 10.99
var amountOfVAT = getVAT(10.99);

// concatenate the amount of VAT variable into a string and
// write into the page.
document.write("Ammount of VAT on 10.99 is: "  +amountOfVAT);


</script>

Live example

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.

Another example (more complex)

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.

<script language="javascript" type="text/javascript">
// define a variable to hold the data + HTML code
var premiershipTable = '';
// create HTML table rows!
// call the getTableRow function passing 3 items of data
// in each instance.  Items of data are seperated with with commas.
premiershipTable += getTableRow('1','Chelsea','86');
premiershipTable += getTableRow('2','Manchester United','85');
premiershipTable += getTableRow('3','Arsenal','75');
premiershipTable += getTableRow('4','Tottenham','70');
premiershipTable += getTableRow('5','Manchester City','67');
premiershipTable += getTableRow('6','Aston Villa','64');
// and so on...

// add the surrounding HTML table code!
// call the addOuterTableCode function passing it the 
// data + html created by the last function
var wholetable = addOuterTableCode(premiershipTable);

// use getElementById to add the table to the 
// <div> named "footyTable"
document.write(wholetable);
    
// define the getTableRow function.
// this function is passed 3 items of data when it is called
function getTableRow(no,team,points) {
    var tablerow = '<tr><td>';
    tablerow += no;
    tablerow += '</td><td>';
    tablerow += team;
    tablerow += '</td><td>';
    tablerow += points;
    tablerow += '</td></tr>';
    return tablerow;
}

// define the addOuterTableCode function
// this function is passed only one item of data when it is called
function addOuterTableCode(rows) {
    var tableCode = '<table id="jsTable">';
    tableCode += '<thead><tr>';
    tableCode += '<th>No.</th>';
    tableCode += '<th>Team</th>';
    tableCode += '<th>Points</th>';
    tableCode += '</tr></thead>';
    tableCode += '<tbody>';
    tableCode += rows;
    tableCode += '</tbody>';
    tableCode += '</table>';
    return tableCode;
}

</script>   

Live example

What next?

For more on functions read W3Schools functions page.

Here is a slightly more complicated function example for you to work through if you want to learn more. You could also look over the Quirksmode functions page.

Exercise!

Now open the functions exercise page and work through it.

You may also use the JavaScript scratch pad to try out code quickly.