Functions

Functions are just collections of JavaScript statements which wait to be executed until they're called on. Think paragraphs. You can give them their own names, too. But functions should be pretty focused (just like a well-focused paragraph with a thesis sentence) so they do only one clear task.

There are two types of functions (just like there are two types of objects): built-in functions (provided to you by JS) and custom functions (ones you can build yourself). You can click on this sentence to see a table of built-in JavaScript functions.

Usually functions are defined at the beginning of a JS block, so if you refer to the function later the program will know exactly what you're talking about--just like you need to define variables early so they can be used.


Calling functions

A function definition begins with the keyword function followed by the name you've assigned to it, and a pair of parentheses. To call the function later you have to enter the name of the function and parentheses.

For example:

<html>

<head>

<script language="JavaScript">

function error_message(){

}

</script>

</head>

<body>

<form>

<input type="button" value="Click here to see your mistakes" onClick="error_message()">

</form>

</body>

</html>

This script creates a little error message function, then summons it in the HTML page. I know we haven't talked about forms yet, but this just creates a button which then calls the error_message function. Copy this into Text Editor, save it, and run it in Netscape.


Passing parameters

Functions often get passed values that they then go to work on; these are called passed parameters. Let's modify that simple little function above and give it a parameter:

<html>

<head>

<script language="JavaScript">

function e_message(Message){

}

</script>

</head>

<body>

<form>

<input type="button" value="Click here to see your mistakes" onClick="e_message('Big mistake')">

</form>

</body>

</html>

You might want to notice that we had to use single quotes inside the double quotes when we called the function error_message. onClick, by the way, is an event handler; see the lecture note on that topic. So when the button is clicked, the message "Big mistake" gets passed to the e_message function, and the alert box pops up.

Here's another slightly more complicated example. This one just asks the user for the number of items purchased, then calculates the total bill, including tax. Notice, though, how the value entered (the number of items) is passed to the bill_calc function. Copy and paste, save it, and run it in Netscape.