MSc-IT Study Material
June 2010 Edition

Computer Science Department, University of Cape Town

Some simple functions

Mathematical functions

A JavaScript function to add two numbers:

	function add()
	{
	document.write( 5+5 );
	}
	add();
      

Table 16.4. Function to display "Hello"

Name (optional)add
Arguments (optional) 
bodydocument.write(5+5)
Returns (optional) 


And functions to perform various other arithmetical operations:


	function minus()
	{

	document.write("<p>" + (6-4) );

	}
	function times()
	{

	document.write("<p>" + 6*4 );

	}
	add();
	minus();
	times();
      

Note: Function naming convention

You should always name your functions and variables with a lower case first letter, unless you are writing a function that will act as a constructor (see later unit). If your function name is made up of a number of words, start the second and subsequent words with an upper case letter to make the names more readable. Examples might include:

  • function calculateTaxTotal()

  • function changeImage()

  • function setCircleRadius()

  • function divide()

Functions that RETURN a value

Most mathematical functions do not display their results in an HTML document: they only calculate and return intermediate results for use by other functions.

For example, the code below uses the Math.pow( value, power ) function to calculate the area of a circle. Also the Math.round() function is used to create roundedArea.

	// calculate circle ara
	var radius = 10;
	var circleArea = 3.1415 * Math.pow( radius, 2 );
	// round to 2 decimal places
	var roundedArea = Math.round( circleArea * 100) / 100;
	document.write( "<p>> Area of circle with radius " + radius + "
	has area of " + circleArea );
	document.write( "<p> rounded area is " + roundedArea );
      

Defining a function that returns a value

Creating a user-defined function that returns a value is straightforward: at some point in the function's execution a return statements needs to be executed. Typically, functions returning a value require arguments that will be used in the calculation of that value.

For example we might wish to define a function addVAT( total ) which adds 14% to a total, and returns this new value. The specification for our function might appear as follows:

Table 16.5. Function to calculate a price, including VAT

Name (optional)addVAT
Arguments (optional)total
bodyreturn (total * 1.14)
Returns (optional)Value representing 14% VAT added to total


	function addVAT( total )
	{
	return (total * 1.175);
	}
	var goodsTotal -=50;
	writeln(" total before tax = " + goodsTotal );
	var newTotal = addVAT(goodsTotal);
	writeln("<p> total with tax added " + newTotal );
      

As can be seen, to make a function return a value we include a return statement after having done the appropriate calculation.

Arguments are named like variables (in fact they can be though of as a kind of local variable). So these named arguments can be referred to in the processing and calculation of the function.

A date Function

The function below displays the current date and time:

	//function name
	function today()
	//begin function statements
	{
	//declare variable dayAndTime
	// and initialise to become a new Date object
	var dayAndTime = new Date()
	//write date to browser page
	document.write("The date is: " + dayAndTime)
	//end function statements
	}
	//invoke function
	today()
      

The above code includes many comments explaining how it functions. Without these comments the function and its invocation would look as follows:

	function today()
	{
	//declare variable dayAndTime
	// and initialise to become a new Date object
	var dayAndTime = new Date()
	//write date to browser page
	document.write("The date is: " + dayAndTime)
	}
	today()
      

The browser output is as follows:

Note

The behaviour of the scripts may vary according to which Web browser you use.

The today function described

This function has been defined with:

	function today() 
	{
	...
	} 
      

The first statement declares a variable called dayAndTime initialised with a Date object. Date was discussed in previous units, and allows access to the current date and time.

Note

JavaScript is case sensitive. The variable dayAndTime is not the same a dayandtime.

It is a good idea to keep all your JavaScript in one case. Lowercase letters, except for the first letter of the second and later words, is the most appropriate choice (unless working with class names).

At this point, the function now has the date and time stored, but has not yet displayed it. The second statement does this:

    document.write("The date is: " + dayAndTime)

In the second statement the document object refers to the primary Web browser window. The method write allows content to be written to the browser.

The output is determined in this particular instance by:

    ("The date is: " + dayAndTime)

The value of variable dayAndTime is converted to text and concatenated (added) to the String "The date is: ".

This new String is sent to the write statement and displayed in the browser window.

Exercise 1

Open a new notepad document and write (or copy) the script for the today function. Save the document as "today.html" (or something similar) and load this HTML document into your Web browser. Your browser should look similar to the following:

Your first task is to familiarise your self with this function.

  1. Change all uses of the function name today() to an alternative name. Save and reload your changed HTML file.

  2. Change dayAndTime to an alternative name. Save and reload your changed HTML file.

  3. Add the window.status = dayAndTime; statement. Remember to use the new name you've given the dayAndTime variable name.

What does this new statement do? Save and reload your changed HTML file.

You can find some thoughts on this exercise at the end of the unit.