7.1 What Is a Function?


A pocket calculator performs certain functions. You push the buttons , send information to the calculator, it performs a calculation, and sends back the results. You don't care about what transpires inside the calculator, you just want the results. That's what a function does. Functions are self-contained units of a program designed to accomplish a specified task such as calculating mortgage payments, displaying random images, or checking for valid input. They can be used over and over again and thus save you from repetitious programming. They are also used to break up a program into smaller modules to keep it better organized and easier to maintain. JavaScript has a large number of its own built-in functions, and now you can create your own.

By definition, a function is a block of statements that not only performs some task, but also returns a value. A function is independent of your program and not executed until called. A function is often referred to as a "black box." It's like the pocket calculator: Information goes into the black box (or calculator) as input and the action or value returned from the box is its output. What goes on inside the box is transparent to the user . The programmer who writes the function is the only one who cares about those details. When you use document.write() , you send something like a string of text to the function, and it sends some text back to the browser. You don't care how it does its job, you just expect it to work. If you send bad input, you get back bad output or maybe nothing, hence the expression "Garbage in, garbage out."

Functions are like mini-scripts. They contain JavaScript statements that behave as a single command and can be called repeatedly throughout a program without rewriting the code.

The terms "function" and "method" are often used interchangeably. A method refers to a function that is used with JavaScript objects (covered in Chapter 8, "Objects"). A function, as used in this chapter, is a standalone block of statements, independent of the program until invoked by a caller.

7.1.1 Function Declaration and Invocation

Functions must be declared before they can be used. Normally functions are placed in the <head> tag of the HTML document to ensure that they are defined before used. Within the <script> tag itself, they can go anywhere . Function definitions can also be located in external JavaScript files (see "JavaScript from External Files" on page 13 of Chapter 1).

To define a function, the function keyword is followed by the name of the function, and a set of parentheses. The parentheses are used to hold parameters, values that are received by the function. The function's statements are enclosed in curly braces.

 
 function bye() { document.write ("Bye, adios, adieu, au revoir..."); } 

Once you define a function, you can use it. JavaScript functions are invoked by calling the function; for example, bye() . A function can be called directly from within the <script> tag, from a link, or called when an event is triggered, such as when the user presses a key. When called, the function's name is followed by a set of parentheses that may contain messages that will go to the function. These messages are called arguments.

To check whether the function has been defined or if it is truly a function, use the typeof operator; for example, typeof(function_name).

FORMAT

graphics/07inf02.gif

Example 7.1
 <html>     <head>     <title>A Simple Function</title>     <script language=JavaScript> 1  function welcome()  {  //  Function defined within <head> tags  2           var place="San Francisco"; 3           alert("Welcome to "+ place + "!"); 4       } 5  welcome();  //  Function call  </script>     </head>     <body bgcolor="lightblue">     <font face="arial" size-"+1">     <center>     <b>San Francisco</b><br> 6   <img src="sf.jpg" width=400 height=300 border=1>     </center>     </body>     </html> 

EXPLANATION

1 Functions must be defined before they can be used. Therefore, functions are normally placed in a JavaScript program, between the HTML <head></head> tags. In this example, the function is defined, but it will not do anything until it is called from somewhere in the file.

The function keyword is followed by the user-defined name of the function called welcome and a set of parentheses. The parentheses are used to hold parameters, information being received by the function. What the function actually does is defined in a set of statements enclosed within curly braces. The function statements are enclosed in a set of curly braces.

2, 3 This is the code that is run whenever the function is called. It is called the function definition. When this function is called, the string San Francisco will be assigned to the variable called place and the alert dialog box will display " Welcome to San Francisco! " in the browser window. (See Figure 7.1.)

Figure 7.1. After the function welcome() is called, output is sent to the browser.

graphics/07fig01.jpg

4 This is the final closing curly brace that ends the function definition.

5 This is where the function is invoked or called. When the function welcome() is called, the statements within its definition will be executed.

6 Since the function is called in the head of the document, this image will not appear until the user presses the OK button in the alert dialog box. (See Figure 7.2.)

Figure 7.2. After the user presses the OK button in the alert box, this image loads.

graphics/07fig02.jpg

Passing Arguments

If a user wants to send values to a function, the values are enclosed in the parentheses right after the function name and sent as a comma-separated list of arguments when the function is called. The arguments are received by the function in a list of corresponding values called parameters. The names of the arguments are not necessarily the same names in the parameter list, but they correspond to the same values. These values can be assigned to local variables within the function. Local variables disappear when the function exits. JavaScript doesn't keep track of the number of arguments sent to the function to make sure they match up with the number of parameters specified in the function definition at the other end. If you send three arguments, and there are only two parameters defined within the function, the third argument is ignored. If you send three arguments, and there are four parameters waiting within the function, then the fourth parameter is undefined . It's similar to sending messages to an answering machine. If you send a message and the message machine is full, your message is ignored, and if you send a message and there's room for more messages, the message you sent is stored, and the unused space is still there, but not defined.

graphics/07inf03.gif

Figure 7.3. In the analogy of the pocket calculator, you are the caller when you press the buttons, and the internal functions inside the calculator are the receiver.

graphics/07fig03.gif

Example 7.2
 graphics/07inf04.gif 

EXPLANATION

  1. The function, greetings () , has one parameter, called pal . This parameter holds a value that is sent to the function when it was called. The parameter name is any valid JavaScript variable name.

  2. The alert method will display the string, "Greetings to you, " concatenated to the value stored in pal ; in this example that value is "Birdman!" .

  3. The JavaScript program is in the body of the document. It contains a function call that will invoke a function defined in the head of the document.

  4. The function greetings() is called with one argument, "Birdman!" . This argument will be sent to the function, and assigned to the parameter, pal . If the function had been called in the head of the document as it was in Example 7.1, the background image would not appear until after the user pressed the OK button in the alert box (see Figure 7.4), but in this example, the image was loaded before the function was called.

    Figure 7.4. Output from the greetings() function in Example 7.2.

    graphics/07fig04.jpg

Calling a Function from a Link

A function can be called directly from a link, by using the JavaScript pseudoprotocol, javascript: , instead of a normal URL. The javascript: protocol and the function call are placed within quotes and assigned to the href attribute of the <a> tag. When the user clicks his mouse on the link, instead of the program going to the URL of another page, a JavaScript function will be called.

Example 7.3
 <html>  <head>  <title>Functions</title> 1   <script language=javascript> 2  function greetings(){  //  Function defined within <head> tags  document.bgColor="lightblue"; 3           alert("Greetings to you!");  }  </script>  </head>  <body><center> 4       <a  href=  "  javascript:greetings()  "><big>Click here for             Salutations</big>         </a><br>     </center>     </body>     </html> 

EXPLANATION

1 The JavaScript program starts here in the head of the document. The function is defined within the head of the document to guarantee that it will be defined before being called.

2, 3 The function greetings() is defined. It is very simple. It causes the background color of the document to be a light blue color and causes an alert box to appear with a greeting message.

4 The href attribute of the link tag is assigned a string consisting of the javascript: pseudoprotocol, followed by the name of the function to be called. When the user clicks on this link, JavaScript calls the function, greetings() . (See Figure 7.5.)

Figure 7.5. After clicking on the link, the function is called, causing the alert dialog box to appear.

graphics/07fig05.jpg

Calling a Function from an Event

An event is triggered when a user performs some action, like clicking on a button or moving his mouse over a link. The function assigned to the event is called an event handler. When the event is triggered, the function is called. In the following example, when the user clicks on the Welcome button, the function is called.

Example 7.4
 <html>     <head<title>Functions and Events</title> 1   <script language=javascript> 2  function greetings()  {  //  Function definition  3           document.bgColor="pink";             alert("Greetings and Salutations! ");         }     </script>     </head> 4   <body><center> 5  <form>  6           <input type="button" 7              value="Welcome button" 8  onClick="greetings();"  >  </form>  </body>     </html> 

EXPLANATION

  1. The JavaScript program starts here. The function is defined in the head of the document.

  2. The function greetings() is defined here.

  3. The body of the function ”what it does ”is found here between the curly braces.

  4. The body of the page starts here.

  5. An HTML form starts here. It will be used to create a button input device.

  6. The type of input device is a button.

  7. The value that will be displayed in the button is "Welcome button" . (See Figure 7.6.)

    Figure 7.6. When the button is pressed, the event is triggered.

    graphics/07fig06.jpg

  8. When the user presses or clicks on the button, the onClick event will be triggered, causing the greetings() function to be called. The value assigned to the onClick event is a JavaScript function enclosed in quotation marks. (See Figure 7.7.)

    Figure 7.7. A function is called after the event is triggered. The function "handles" the event.

    graphics/07fig07.jpg

Calling a Function from JavaScript

In the first examples of this chapter, functions were defined in one JavaScript program and called from another. Although it is valid to define and call the function from the same JavaScript program, it is often desirable to define the function in the head of the document, to be sure it has been defined before it is called. Then you can call the function from a link, an event, or another JavaScript program. Since the document is defined within the <body></body> tags, the body is often the place from where you will call functions. The general rule of thumb is: If your script is designed to write data to the page, put the <script></script> tags within the <body></body> tags. Example 7.2 called a function from one JavaScript program within the body, but defined the function in another JavaScript program within the head.

Scope of Variables in Functions

The scope of a variable describes where the variable is visible in the program; that is, where it can be used in the program. Variables declared outside of functions are global in scope, meaning they can be used or changed anywhere in the program. If a variable is declared within a function with the var keyword, then the variable is local in scope ”the variable can be used only within the function where it is defined.

Example 7.5
 <html>     <head><title>Function Scope</title>     <script language=javascript> 1  var name="William";  2  var hometown="Chico";   function greetme(){  3  var name="Daniel";  //  Local variable  document.bgColor="lightblue"; 4           document.write("<h2>In function, <em>name</em> is "                            +  name  ); 5           document.write(" and <em>hometown</em> is "+  hometown  ); 6       } 7  greetme();  8       document.write("<br>Out of function, <em>name</em> is "                        +  name  ); 9       document.write(" and <em>hometown</em> is " +  hometown  );     </script>     </head>     </html> 

EXPLANATION

  1. The variable called name is global in scope. It is visible throughout the JavaScript program.

  2. The variable called hometown is also global in scope and is visible throughout the program.

  3. Any variables declared within a function with the var keyword are local to that function. In fact, you must use the var keyword when declaring local variables; otherwise , the variables will be global. The variable called name has been declared inside the function. This is a local variable and has nothing to do with the variable of the same name on line 1. This variable will go out of scope when the function ends on line 6, at which point the global variable will come back in scope.

  4. The variable called name was defined inside this function and is local in scope. It will stick around until the function exits.

  5. The global variable called hometown is visible here.

  6. The closing curly brace marks the end of the function definition.

  7. The function greetme() is called here.

  8. The global variable called name has come back into scope.

  9. The global variable called hometown is still in scope. (See Figure 7.8.)

    Figure 7.8. Output from Example 7.5.

    graphics/07fig08.jpg

7.1.2 Return Values

Functions may return values with a return statement. The return keyword is optional and can only exist within a function. When the return keyword is reached in a function, no further processing within the function occurs. A return can be used to send back the result of some task, such as a calculation, or to exit a function early if some condition occurs. If a function doesn't have a return statement, it returns the undefined value.

FORMAT

 
 return; return expression; 

Example :

 
 function sum (a, b) {     var result= a + b;     return result; } 

If the call to the function is made part of an expression, the returned value can be assigned to a variable. In the following example the sum function is called with two arguments, 5 and 10 . The sum function's return value will be assigned to the variable total .

 
 var total=sum(5, 10); 
Example 7.6
 graphics/07inf05.gif 

EXPLANATION

  1. A function called mileage() is defined in this JavaScript program.

  2. The return statement sends back to the caller of the function the result of the division. That returned value will be assigned to the variable, rate , on line 4.

  3. The user is asked for input. The number of miles driven and the amount of gas used are assigned to the variables called distance and amount , respectively. (See Figure 7.9.)

    Figure 7.9. The user is asked for input.

    graphics/07fig09.jpg

  4. The mileage() function is called, passing two arguments. Since the mileage() function is on the right-hand side of the assignment operator (the = sign), whatever is returned from the function will be assigned to the variable, called rate , on the left-hand side of the = sign.

  5. The alert dialog box displays the value returned from the function: the number of miles used per gallon. (See Figure 7.10.)

    Figure 7.10. The number miles per gallon is returned by the mileage() function.

    graphics/07fig10.jpg

Recursion

Definition of recusion:

recursion : See recursion.

The above definition is a well-known joke in the computer world. JavaScript supports recursion. So what is it? A recursive function is a function that calls itself. It's a chain of function calls to the same function. The first time it calls itself is the first level of recursion, the second time is the second level, and so on. When a function calls itself, execution starts at the beginning of the function, and when the function ends, the program backs up to where it was when it called the function and starts executing from that point. Most importantly there must be a way to stop the recursion, or it will be infinite, and probably cause the program to crash.

Example 7.7
 <html>     <head>     <title>Recursion</title>     <script language=JavaScript> 1  function upDown(num)  { 2           document.write("<b><font size='+1'>  Level  "                            +  num  + "</b><br>"); 3           if(num < 4){ 4  upDown(num + 1);  //  Function calls itself  5              document.write("<em>Level "+ num + "<em><br>");             }         }     </script>     </head>     <body bgcolor="lightblue">     <h2>Recursion</h2>     <script language="JavaScript"> 6  upDown(1);  </script>     </body>     </html> 

EXPLANATION

  1. The first time this function is called it is passed the number 1.

  2. The function prints out the level number, Level 1.

  3. If the value of num is less than 4 , the function calls itself.

  4. When the function calls itself, it adds 1 to the value of num . When the function calls itself it restarts execution at the top of the function, this time with the value of num equal to 2 . Each time the function calls itself, it creates a new copy of num for that recursion level. The other copy is on hold until this one is finished. The function keeps calling itself and printing level numbers in bold text until the if statement fails; that is, until the value of num is not less than 4.

  5. This line won't be executed until the recursion stops ”when the value of num is 4 . When that happens, the current version of upDown() is finished, and we back off to the previous called function and start execution at line 5. This process continues until all of the functions have completed execution.

  6. This is the first call to the upDown() function. The argument is the number 1 . The output is shown in Figure 7.11.

    Figure 7.11. Output from Example 7.7.

    graphics/07fig11.jpg

7.1.3 Functions Are Objects

For a discussion on how functions behave as objects, see "Creating the Object with a User-Defined Function" on page 133 in Chapter 8.



JavaScript by Example
JavaScript by Example (2nd Edition)
ISBN: 0137054890
EAN: 2147483647
Year: 2003
Pages: 150
Authors: Ellie Quigley

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