Next page | Contents page |

Functions

function name (parameters)
{

  statements
}


A function is like a little machine that can be called into use repeatedly. Just give it different inputs each time. It will carry out a particular computation and have some effect, which may be a value returned as a result. Once you, or someone else, has written a function and documented what it does and how to use it, you can then forget about its inner workings and treat it as a black box. Put values in, turn the handle, get a result.

We have seen several examples of functions already. There are two aspects: the declaration of the function and its invocation.

The declaration of a function must start with the keyword function. That is usually followed by an identifier, to give the function a name that can be used to invoke it (or call it). It is not always necessary to give a function a name, as we will see later.

The function declaration must then have a pair of parentheses, (), which may or may not have something between them. That something would be a comma-separated list of parameters: values to be passed into the function when it is invoked.

Then follows the body of the function, containing executable statements. The body must be enclosed in curly braces, {}.

alert()

alert() is a predefined function if you are using JavaScript in a browser. It may not be available in other environments.

Here is an example of declaring a function that has no input parameters:


function hello () 
{
  alert ("Hello world!"); 
}

That calls a standard library function, alert(), which pops up a simple window containing a message and an OK button for closing the window again.

Our function called hello is invoked like this, from anywhere else in our program:


  hello ();

The next example modifies that so that part of the message is passed into the function as a parameter:


function hello2 (name)
{
  alert ("Hello " + name);
}

This is a more reuseable function because we can invoke it with any name we like:


  hello2 ("Jane Smith");
  var firstName = "Tommy";
  var lastName = "Atkins";
  hello2 (firstName + " " + lastName);

Reuseability is a useful characteristic of functions. If you find you are writing similar code over and over again, with just a few values different, put that code in a function and make the varying things parameters of that function.

Scope of variables

Any variables declared inside a function no longer exist when the function returns. They cannot be accessed from outside the function.

On the other hand, global variables, declared at the top level outside any functions, are accessible from within a function. Try not to access global variables from within functions because it makes the functions less self-contained. But sometimes it is a reasonable thing to do because it results in much simpler code than passing everything into a function as parameters.

Here is a function having four input parameters, the x and y coordinates of two points:


function distance (x1, y1, x2, y2)
{
  var dx = x1 - x2;
  var dy = y1 - y2;
  return Math.sqrt (dx * dx + dy * dy);
}

Some arithmetic is done to calculate the distance between the 2 points. That involves invoking another function, a standard function called sqrt() which is part of a library object called Math. The sqrt() function calculates the square root of its single input parameter.

That last example used the keyword return to return the result to the invoker, so it could be assigned to another variable like this:


  var d = distance (2, 5, 5, 9);

We will soon see that it is possible to write the distance() function differently so that it takes two parameters of type Point, each of which has an x and a y component. That maps more appropriately onto the real geometrical set-up.

NB: Unlike many other programming languages, JavaScript does not enable you to say anything about the data types of input parameters or return values. That increases the risk of mistakes so you must be careful. The hello2() function took in a String and returned nothing at all but distance() takes in 4 Numbers and returns a Number. When calling a function you must take care to give suitable input values and treat any return appropriately.

There is much more to functions in JavaScript, as we will discover after introducing Objects and Arrays.

Next page | Contents page |