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 InvocationFunctions 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
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
Passing ArgumentsIf 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.
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.
Example 7.2EXPLANATION
Calling a Function from a LinkA 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
Calling a Function from an EventAn 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
Calling a Function from JavaScriptIn 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 FunctionsThe 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
7.1.2 Return ValuesFunctions 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.6EXPLANATION
RecursionDefinition 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
7.1.3 Functions Are ObjectsFor a discussion on how functions behave as objects, see "Creating the Object with a User-Defined Function" on page 133 in Chapter 8. |