Functions


As we've already seen, a function is a set of statements that run when you call them, and not before, and you can call a function by treating its name as an expression to be evaluated. Here's the formal syntax for creating a function using the function statement:

 function  name  ([  param1  ] [,  param2  ] [...,  paramN  ]) {  statements  } 

The following parts comprise this statement:

  • name . The name of the function. (The same rules for naming variables apply.)

  • param1 to paramN . The names of arguments to be passed to the function; using these arguments, you can pass data to the function for the function to work on. In JavaScript, a function can have up to 255 arguments.

  • statements . The statements that make up the body of the function and which are executed when the function is called.

Functions are integral to JavaScript, and they've been around since the beginning, as you see in Table 3.9.

Table 3.9. The function Statement

Statement

NS2

NS3

NS4

NS6

IE3a

IE3b

IE4

IE5

IE5.5

IE6

function

x

x

x

x

x

x

x

x

x

x

Here's an example that we've already seen as far back as Chapter 1, "Essential JavaScript." In this example, we're connecting a function named alerter to an HTML button, using that button's ONCLICK event attribute. Here, the body of the function is just one statement, which displays an alert box with the message You clicked the button! when the function is called:

(Listing 03-09.html on the web site)
 <HTML>      <HEAD>          <TITLE>Executing Scripts in Response to User Action</TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function alerter()   {   alert("You clicked the button!")   }  // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Executing Scripts in Response to User Action</H1>          <FORM>  <INPUT TYPE="BUTTON" ONCLICK="alerter()" VALUE="Click Me!">  </FORM>      </BODY>  </HTML> 

This shows us the basics of creating a functionyou just use the function keyword, followed by the name you want to give to the function (you can use any valid JavaScript namesee the discussion of valid names at the beginning of the preceding chapter), followed by a parentheses-enclosed list of parameters used to pass data to the functionwe won't use any parameters here, so the parentheses are emptyand the body of the function, enclosed in curly braces. The function in this example is called when the user clicks the button, and it displays an alert box, as you see in Figure 3.6.

Figure 3.6. Using a function.

graphics/03fig06.gif

The value of placing the code in alerter in a function is that it isn't run until you call the function (if you just put code in a <SCRIPT> element, on the other hand, that code is run automatically when the page loads). However, functions can do a great deal more than just this.

Returning Values

Functions are often used to perform calculations, and they can return a value. If a function returns a value, you can use its name as an expression in your code, and JavaScript will replace that expression with the value returned by the function.

To return a value from a function, you use the return statement. Here's the syntax of that statement:

 return  expression  

In this case, expression evaluates to the value you want to return from the function. The return statement has been around as long as JavaScript has, as you see in Table 3.10.

Table 3.10. The return Statement

Statement

NS2

NS3

NS4

NS6

IE3a

IE3b

IE4

IE5

IE5.5

IE6

return

x

x

x

x

x

x

x

x

x

x

For example, here's how I create a function, getPi , that returns the value of pi (using the JavaScript Math.PI property) when called:

(Listing 03-10.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Using the return Statement          </TITLE>      </HEAD>      <BODY>          <H1>Using the return Statement</H1>          <SCRIPT LANGUAGE="JavaScript">              <!--  function getPi()   {   return Math.PI   }   document.write("pi = " + getPi())  // -->          </SCRIPT>      </BODY>  </HTML> 

Figure 3.7 shows the results of this code.

Figure 3.7. Returning a value from a function.

graphics/03fig07.gif

Tip

Although not a problem in current browsers, some older browsers may have trouble if you call a function before defining it. Note also that for the sake of organization, it's often a good idea to place your functions together in a <SCRIPT> element in the head section of you web page (unless the code in a function writes to the document body, in which case the code should go in the body section of the page).


You also can pass values to functions, as we've seen.

Passing Values

To pass data to a function so that it can work on that data, you can pass arguments (also called parameters ) to the function. Here's an example; in this case, I'll write a function named adder that adds two arguments passed to it and returns their sum. When you set up the function, you indicate how many parameters it takes and what names you want to give to those parameters in the argument list inside parentheses:

 function adder(operand1, operand2)  {      .      .      .  } 

Here, I've indicated that this function takes two parameters. I've named the first parameter operand1 and the second parameter operand2 . Now if I call adder like this: adder(2, 5) , then in the function's body, the variable operand1 will hold 2, and the variable operand2 will hold the value 5. That makes things easyall I have to do to get the sum of these operands is to add operand1 and operand2 and return the result in the body of the function, as follows :

(Listing 03-11.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Passing Data to Functions          </TITLE>      </HEAD>       <BODY>          <H1>Passing Data to Functions</H1>          <SCRIPT LANGUAGE="JavaScript">              <!--  function adder(operand1, operand2)   {   return operand1 + operand2   }  document.write("2 + 5 = " + adder(2, 5))              // -->          </SCRIPT>      </BODY>  </HTML> 

Figure 3.8 shows the results; we learn that, surprisingly, 2 + 5 = 7.

Figure 3.8. Passing values to a function.

graphics/03fig08.gif

Passing by Reference Versus Passing by Value

Now that we're discussing passing data to functions, you should know that you can pass data in two ways: by reference and by value . When you pass data by value, you pass only a copy of that data. When you pass data by reference, however, you're passing direct access to that data. In JavaScript, all data is passed to functions by value, except objects, which are passed by reference.

The upshot is that when you pass data, not objects, to a function, only a copy of that data is passed; so if you change that data, you're only changing the copy of the original data, which means the original data isn't affected. If you pass an object, such as a String object or an Array object, however, the function has direct access to the original object, which means that if you change the values in the object, the original object is affected.

Let's make this less theoretical with an example. In this case, I'll pass both a simple text string and an Array object to a function. Inside the function body, the function's code will change both the text in the string and an element in the array. When the function is done, we'll see that the element in the Array object was indeed changed, whereas the simple text variable was not:

(Listing 03-12.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Passing by reference and by value          </TITLE>      </HEAD>      <BODY>          <H1>Passing by reference and by value</H1>          <SCRIPT LANGUAGE="JavaScript">              <!--  function change(obj, text) {   obj[2]=5   text = "Changed text"   }   var array1 = new Array(1, 2, 3, 4), text = "Original text."   change(array1)   document.write("array1[2] = " + array1[2] + "<BR>text = " + text)  // -->          </SCRIPT>      </BODY>  </HTML> 

You can see the results of this code in Figure 3.9. As this figure shows, the text string variable's value was not changed by the function, but the data in the array was . The result is that you should be aware that when you pass an object to a function, that function has access to the actual object you've passed, not just a copy of it.

Figure 3.9. Passing by reference and by value.

graphics/03fig09.gif

In JavaScript terms, what's really passed when you pass an object is an object reference . An object reference can be thought of as a special data item that stands for the object itself. When you store a reference to, say, a document object in a variable, you can use that variable from then on as you would the document object itself. (Behind the scenes, a reference holds the actual location of the object in memory, giving you direct access to that object.)

Tip

Why does JavaScript pass objects by reference? It does that to save time and resourcessome objects can be very big, and if JavaScript had to create a copy of such objects when they were passed to a function, that could waste a lot of time and browser memory. Passing an object reference, which is a small data item that holds the location of the object in memory, not the object itself, is much more efficient.


Handling Recursion

Here's another aspect of functions that is good to know: Functions can actually call themselves . This process is called recursion , and it can be useful if you're clever and can divide a programming task into a number of identical levels.

Recursion is not something you'll probably use a lot, so feel free to skip this section. Because JavaScript supports it, however, we'll take a look at it here for completeness. The usual recursion example is to compute a factorialthe factorial of a positive integer is the product of that integer times the integer minus one times the integer minus two all the way down to one. Got that?

I'll create an example here to help. 6 factorial, which is written as 6! , is equal to 6 * 5 * 4 * 3 * 2 * 1 = 720. In programming terms, this can be broken up into identical stages, with the following rule for each stage, where I'm computing the factorial of n . First check whether n equals 1, in which case the factorial is done. Otherwise, just multiply n by the factorial of n -1 (which means calling the factorial function againfrom the code inside that function). Here's how it looks in code, where I'm asking JavaScript to compute 6! :

(Listing 03-13.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Using Recursion          </TITLE>      </HEAD>      <BODY>          <H1>Using Recursion</H1>          <SCRIPT LANGUAGE="JavaScript">              <!--  function fact(x)   {   if (x == 0) {   return 1   } else {   return x * fact(x - 1)   }   }   document.write("6! = " + fact(6))  // -->          </SCRIPT>      </BODY>  </HTML> 

You can see the results of this code in Figure 3.10, where, using recursion, we learn that 6! does indeed equal 720.

Figure 3.10. Using recursion.

graphics/03fig10.gif



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net