IWATS - JavaScript

Functions

A function is a block of code that will be executed from a call or when that function is executed. It is a set of JavaScript statements, each statement separated by a semicolon (;). You can call on the same function several times from the same script. There are two different types of functions, user-defined and pre-defined. They are defined in the head of a webpage inside the script tags. You can then call on them throughout that page. If you want to use a certain function on more than one webpage, you need to link externally to the function in the header of each document that uses that function. The introduction in the course notes tells you how to do this.

Defining a Function

You declare a function by stating function, then the name, then a list of arguments, followed by the block of code inside the brackets {}. Below in Figure 7.1 you can see a function named createdON defined that alerts a user that the webpage was created by Aeolus.

Figure 7.1
<script language="JavaScript" type="text/javascript">

function createdON()
{
alert("This webpage was created by Aeolus."
}

</script>

The function above contains no argument set, however a blank set of parenthesis is still required. The argument set refers to the values that were passed to the function by a function call from a form or other location within the document. By placing a function in the head of a document you are ensuring that all the script will be loading up before the function call takes place.

Return Statement

Sometimes you will want a function to return a value after executing a block of code. As on a form when a user needs to enter their name, you want the function to look at the name and determine if the name is valid, and then return true if it is. Making sure the name has no numbers or erroneous characters in it. Below in Figure 7.2 is a function that looks at rank to determine if the candidate holds a valid rank for a commander, and returns true if it is or false if it isn't.

Figure 7.2
<script language="JavaScript" type="text/javascript">

function cmdrRankCheck(rank)
{
  if (rank == CM || rank == CPT || rank == MAJ || rank == LC || rank == COL)
  {
    return true;
  }
  else ()
  {
    return false;
  }
}

</script>

You don't always have to return true or false, you can also return values. If you were to make a calculator using JavaScript on the web you would want to return the answer to whatever the user keyed in which would be any series of numbers.