Previous: Entering Scripts in Your Web Documents Next: Working with Variables

Creating Functions in JavaScript

A function can be thought of as a mini-program within your script. Generally, a function is designed to accomplish one particular task and then return a value to the main body of the script. Functions start by being passed a particular value. That value is then used in calculations or as part of a procedure. Then, in most cases, the function will return a new value to the body of the script, where something else may or may not happen.

Although it's perfectly possible to have an entire script in the body of your document (and you will, occasionally), you'll find that this sort of procedural programming is both wasteful and limited. By breaking your scripts into functions and function calls, you gain two advantages.

First, the functions don't have to be used in any particular order, just like you don't have to click the icons in Microsoft Windows or Macintosh applications in any particular order. So, a script can be changed around or used with event handlers to call the functions in any order.

Second, functions can be reused. You can use different data with the same function to get different results. If the function is flexible enough, it will save you quite a bit of programming to simply call the function whenever its particular capabilities are required.

However, functions do need to be declared, or defined, usually in the <head> of your Web document. Then, the functions have to be called, or launched, usually from within the Web page itself.

Declaring Functions

Declaring a function is when you tell the browser, "I'm going to have this function, and this is what it's going to do." When the browser loads a page, it will make note of the different functions that you've declared so that it knows to return to them when they're called.

Most script authors will declare their JavaScript functions in the <head> of their Web documents, although that isn't strictly required. They can be declared anywhere within the document. The function declaration needs to appear inside a <script> container, and you're free to place more than one <script> container in a document. In fact, JavaScript is a little weird because all the <script> elements, taken together, comprise the script. (In most programming, your script isn't broken up with HTML and XHTML markup in-between the functions and function calls.)

Here's the basic format for a function call:

<script type="text/javascript">
<!-- hide script
 function function_name(incoming_value) {
 ...function code...
 return (new_value)
}
// end hiding -->
</script>

Remember that when a script calls a function, it often sends along a value. In your function definition, you'll need to assign a name to that passed value, which is represented by incoming_value. If the function is designed to perform simple math, for instance, you might call the incoming value first_num or something similar. You can then use that name in formulas, such as new_num = first_num * 3.

When you give the incoming value a name, you're creating a variable. Then the computer reserves some memory for that variable and gives it a name. You can then assign a certain value to that name and use that name in your script. For instance:

  1. In the body of your script, you send the value 5 to a function.

  2. The function receives that value and creates a variable called my_number to which that value is assigned.

  3. Then you tell the script to "add 10 to my_number" using a formula such as

    new_number = my_number + 10 
  4. If you did it right, the script returns the answer using the variable new_number to the body of the script.

  5. The body of the script accepts that new value, and the answer is 15.

Along with that variable, note the keywords function and return. The function keyword is always the beginning of a function declaration, followed by the name of the function and, in parentheses, the variable name to be assigned to the incoming value. The return keyword is used to end the function declaration—it's telling the function to return the parenthetical value to the portion of the body of the script that called this function in the first place.

Also, notice that the entire calculating part of the function is between curly brackets, between the two keywords. An example of a function declaration might be

<script type="text/javascript">
<!--
function getSquare (num) 
{
  squareNum = num * num;
  return (squareNum);
}
// end hiding -->
</script>

In this example, you've created a function called getSquare, which accepts a value, names it num, and then multiplies that value by itself and assigns the resulting value to a variable named squareNum. Finally, it returns that value to the body of the script.

At least, that's what the function has been declared to do. It won't actually do it yet because it doesn't know which actual values to work with until you call the function from within the body of the script.

Function Calls and Value Return

Generally, the body of your script will be just a series of function calls. There isn't a whole lot of calculating done in the guts of your script. You send a value out to a function to be computed and then receive the results back in the body. A function call either appears inside a <script> container, in an event-handler attribute (see "JavaScript and User Input," which also is available online), or in an URL. A typical function call looks like this:

function_name(value);

You can put a variable name, an actual number, or a string of text in the parentheses, as long as the function is designed to accept such a value. (Function calls in the body of your document need to be surrounded by <script> tags, just like the function definitions in the head of the document.)

NOTE

Your function calls must always pass a value type that the function expects. If you pass a string of text to a function designed to perform math functions, you won't get anything useful in return.

As an example, consider the following script that might appear in the body of a document. This script will call the getSquare function created in the previous section:

<script type="text/javascript">
<!-- 
myNum = 10;
mySqr = getSquare (myNum);
document.writeln ("The square of " + myNum + " is " + mySqr + ".");
//-->
</script>

Here's what is happening in this function call:

  1. You've assigned the value 10 to the variable myNum.

  2. Then that variable (and hence the value 10) is passed to the function getSquare. (This example assumes we're using the same function created in the previous section, "Declaring Functions.")

  3. When that number gets up there to the function, it's assigned to the variable num and then the computation occurs.

  4. After the computation, the new value is passed back to the function call in the body of the script.

  5. Here's the interesting part. The entire function call is replaced with the value that is passed back from the function declaration. In this example, the entire call getSquare (myNum) is replaced with the value of 25.

  6. As a result, the variable mySqr is assigned the value of 25, thanks to that equals sign in the script line.

In JavaScript (and in most computer programming), a variable followed by an equal sign is an assignment. In this case, there are actually two. First, you assign myNum = 10, and then you assign mySqr = getSquare (myNum). What you're telling the script is, "Set the variable mySqr equal to the value of the function getSquare when we send it the value myNum."

In JavaScript, the equal sign is used to assign values to variables. So when you type countNum = 12, it isn't a question. You've told the browser that the number 12 is now the value of the variable countNum. This is in contrast to a comparison, which is represented by two equal signs (==). You use the comparison when you want the script to decide whether or not two values are equal. You'll see more on variables and comparisons later in the section "Controlling Your JavaScript."

Function Call Example

Building on the function call and return process that we've discussed so far, let's take a look at a sample document that incorporates the entire script that's been used as an example in this section. Listing 2 shows the whole thing coming together.

Listing 2 Function Call and Return

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Squared</title>
<meta http-equiv="Content-Script-Type" content="text/javascript">

<script type="text/javascript">
<!--hide scripting
function getSquare (num) 
{
  squareNum = num * num;
  return (squareNum);
}
//end hiding -->
</script>
</head>

<body>
<h1>Here's the answer:</h1>
<script type="text/javascript">
<!--hide scripting
myNum = 10;
mySqr = getSquare (myNum);
document.writeln ("The square of " + myNum + " is " + mySqr + ".");
// end hiding -->
</script>

<noscript>
<p>Your browser doesn't appear to support JavaScript.</p>
</noscript>

</body>
</html>

As you can see, you can incorporate regular markup with the script's function call. After the processing, the variables all have values and the document.writeln() method is able to put the answer onscreen in the browser window, as shown in Figure 3.

Figure 3 This Web page's second line is the result of a function call and returned value.

Previous: Entering Scripts in Your Web Documents Next: Working with Variables