Functions

Functions let you re-use code. You can write it once, then use it many times. They also organise your code. We'll use them to take some gnarly bits of code, and wrap them up so that they're easier to use.
  1. Defining a Function
  2. Returning a value
  3. Magic Functions
  4. Re-using functions between web-pages

Defining a Function

To define a function, you use the keyword function, followed by a name, a list of variables, and a block of code enclosed in curly brackets (which can return a value, although it doesn't have to). It looks something like this:

function myFunction(myvar1, myvar2) {
    // the function's code
    sum = myvar1 + myvar2;
    document.write(sum);
    return sum;
}

This doesn't do anything at first. You have to call the function before the code is run. But once you've defined a function, you can call it from any piece of JavaScript like this:

answer = myFunction(10, 5);

Returning a value

The variable answer in the example above will catch the object returned by myFunction (which in this case will be the number 15). Note the keyword return in the function. Return means: leave the function now, returning this object. You can have several returns in a function. E.g:

// Convert numbers into words
function anotherFunction(myvar) {
    if (myvar == 1) {
        return "One";
    }
    if (myvar == 2) {
        return "Two";
    }
    return "I can't count that high";
    // Any code below here would never be run.
}

Return ends the function. Whichever return is reached first will end the function then and there.

Magic Functions

This section will grow as we meet more of these The following functions are very useful. They draw on some aspects of JavaScript that we won't cover in this course. However you don't have to understand how they work in order to use them.

Choosing Randomly


// This function takes an array as input, and returns a randomly chosen element.
function pickRandom(myarray) {
    x=Math.floor( Math.random() * myarray.length);
    return myarray[x];
}

Example of using it:

// Create an array of quotes about computing
a=["To err is human, but to really foul things up you need a computer. (Paul Ehrlich)",
"Just remember: you're not a 'dummy', no matter what those computer books claim. The real dummies are the people who, though technically expert, couldn't design hardware and software that's usable by normal consumers if their lives depended upon it. (Walter Mossberg)",
"For a long time it puzzled me how something so expensive, so leading edge, could be so useless, and then it occurred to me that a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are, in short, a perfect match. (Bill Bryson)",
"Computer Science: 1. A study akin to numerology and astrology, but lacking the precision of the former and the success of the latter. 2. The boring art of coping with a large number of trivialities. (Stan Kelly-Bootle)",
"Man is the best computer we can put aboard a spacecraft...and the only one that can be mass produced with unskilled labor. (Wernher von Braun)",
"If there's one thing that computers do well, it's to make the same mistake uncountable times at inhuman speed. (Peter Coffee)"];

// Pick one
quote = pickRandom(a);

// Display it
document.write(quote);

This produces a random quote:
Reload the page and you'll get a different one.

Getting the Date

To get the date, we need to create a Date object. This is an aspect of JavaScript that we haven't seen yet (and won't use again on this course). So far, we have created either 'basic' objects (numbers, strings, and arrays) or used Html to create objects (e.g. images using the <img> tag). There is also another way, using the new keyword, which we use here:

function getDateString() {
    now = new Date();
    bits = now.toString().split(" ");
    // Arrays, which we use to convert numbers from the date object into strings
    days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
    months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
    mystring = days[now.getDay()-1] + ", " + now.getDate() + " " + months[now.getMonth()];
    return mystring;
}

We can now use this as follows:

document.write( getDateString() );

Today's date is

Warning: There are a couple of eccentricities in how Date works. The days run from 1 to 7 (i.e. they don't start at 0). However the months run from 0 to 11. The year starts from 1900 (so this year is 105) - just add 1900 to get the correct year.

setTimeout: Animating a Clock

Normally JavaScript either runs (a) when the web-page loads, or (b) in response to an event such as a MouseOver. However we can also get JavaScript to run after a fixed delay. This lets us make features that update regularly (e.g. clocks and stock-tickers) or perfrom animation. We do this by using the special function setTimeout("javascript code", interval). "javascript code" gives some code to execute (normally calling a function). interval gives a period in milliseconds to wait before doing so. So the line:
setTimeout("alert('Hello')", 5000);
would wait 5 seconds, then pop up an alert box saying 'Hello'.

By repeatedly calling setTimeout(), we can make continuing updates or animations. The example below shows how to write a javascript clock:

First create a display for the clock. We use a dummy form with a text element that we can get hold of by id.
<form>
<input id="Clock" type="text" size="8" >
</form>
<script>
// Now define a function to update the clock
function setClock() {
     theDate = new Date();
     theTime = theDate.getHours() + ":" + theDate.getMinutes() + ":" + theDate.getSeconds();
     document.getElementById("Clock").value = theTime;
     // By calling setTimeout again, this function will run every 1/2 a second.
     setTimeout("setClock()",500);
}
// Now start the clock going...
setClock();
</script>


Warning: You can't use document.write() with setTimeout(). Technically, you shouldn't use document.write() with any code that gets run after the page is loaded. Some JavaScript functions let you get away with it, but some are fussier. setTimeout is one of the fussy ones.

In the clock example above, we get round this by using a 'dummy' form with a text element. By setting the value of the text element, we can display changing text to the viewer.

Re-using functions between web-pages

You can place your functions in a separate file, which you then use in different pages. To do this, you create a pure JavaScript file (e.g. myJavaScriptFunctions.js), which you include using
<script src="myJavaScriptFunctions.js"></script>
See the page on Embedding: How JavaScript fits into Html when I write it...