Sams Teach Yourself JavaScript in 24 Hours Free Open Book

Sams Teach Yourself JavaScript in 24 Hours

Previous Page
Next Page

Using Functions

The scripts you've seen so far are simple lists of instructions. The browser begins with the first statement after the <script> tag and follows each instruction in order until it reaches the closing </script> tag (or encounters an error).

Although this is a straightforward approach for short scripts, it can be confusing to read a longer script written in this fashion. To make it easier for you to organize your scripts, JavaScript supports functions, which you learned about in Hour 3, "Getting Started with JavaScript Programming." In this section, you will learn how to define and use functions.

Defining a Function

Functions are groups of JavaScript statements that can be treated as a single unit. To use a function, you must first define it. Here is a simple example of a function definition:

function Greet() {
    alert("Greetings.");
}

This defines a function that displays an alert message to the user. This begins with the function keyword. The function's name is Greet. Notice the parentheses after the function's name. As you'll learn next, the space between them is not always empty.

The first and last lines of the function definition include braces ({ and }). You use these to enclose all of the statements in the function. The browser uses the braces to determine where the function begins and ends.

Between the braces, this particular function contains a single line. This uses the built-in alert() function, which displays an alert message. The message will contain the text "Greetings."

By the Way

Function names are case sensitive. If you define a function such as Greet() with a capital letter, be sure you use the identical name when you call the function.


Now, about those parentheses. The current Greet() function always does the same thing: Each time you use it, it displays the same message. Although this avoids a bit of typing, it doesn't really provide much of an advantage.

To make your function more flexible, you can add parameters, also known as arguments. These are variables that are received by the function each time it is called. For example, you can add a parameter called who that tells the function the name of the person to greet. Here is the modified Greet() function:

function Greet(who) {
    alert("Greetings, " + who);
}

Of course, to use this function, you should include it in an HTML document. Traditionally, the best place for a function definition is within the <head> section of the document. Because the statements in the <head> section are executed first, this ensures that the function is defined before it is used.

Listing 6.1 shows the Greet() function embedded in the header section of an HTML document.

Listing 6.1. The Greet() Function in an HTML Document

<html>
<head>
<title>Functions</title>
<script
language="JavaScript" type="text/javascript">
function Greet(who) {
    alert("Greetings, " + who);
}
</script>
</head>
<body>
This is the body of the page.
</body>
</html>

By the Way

As usual, you can download the listings for this hour or view them online at this book's website.


Calling the Function

You have now defined a function and placed it in an HTML document. However, if you load Listing 6.1 into a browser, you'll notice that it does absolutely nothing. This is because the function is definedready to be usedbut we haven't used it yet.

Making use of a function is referred to as calling the function. To call a function, use the function's name as a statement in a script. You will need to include the parentheses and the values for the function's parameters. For example, here's a statement that calls the Greet function:

Greet("Fred");

This tells the JavaScript interpreter to transfer control to the first statement in the Greet function. It also passes the parameter "Fred" to the function. This value will be assigned to the who variable inside the function.

By the Way

Functions can have more than one parameter. To define a function with multiple parameters, list a variable name for each parameter, separated by commas. To call the function, specify values for each parameter separated by commas.


Listing 6.2 shows a complete HTML document that includes the function definition and a second script in the body of the page that actually calls the function. To demonstrate the usefulness of functions, we'll call it twice to greet two different people.

Listing 6.2. The Complete Function Example

<html>
<head>
<title>Functions</title>
<script language="JavaScript" type="text/javascript">
function Greet(who) {
    alert("Greetings, " + who);
}
</script>
</head>
<body>
<h1>Function Example</h1>
<p>Prepare to be greeted twice.</p>
<script language="JavaScript" type="text/javascript">
Greet("Fred");
Greet("Ethel");
</script>
</body>
</html>>

This listing includes a second set of <script> tags in the body of the page. The second script includes two function calls to the Greet function, each with a different name.

Now that you have a script that actually does something, try loading it into a browser. You should see something like Figure 6.1, which shows the Greeting script running in Firefox.

Figure 6.1. The output of the Greeting example.


By the Way

Notice that the second alert message isn't displayed until you press the OK button on the first alert. This is because JavaScript processing is halted while alerts are displayed.


Returning a Value

The function you just created displays a message to the user, but functions can also return a value to the script that called them. This allows you to use functions to calculate values. As an example, you can create a function that averages four numbers.

Your function should begin with the function keyword, the function's name, and the parameters it accepts. We will use the variable names a, b, c, and d for the four numbers to average. Here is the first line of the function:

function Average(a,b,c,d) {

By the Way

I've also included the opening brace ({) on the first line of the function. This is a common style, but you can also place the brace on the next line, or on a line by itself.


Next, the function needs to calculate the average of the four parameters. You can calculate this by adding them, and then dividing by the number of parameters (in this case, 4). Thus, here is the next line of the function:

result = (a + b + c + d) / 4;

This statement creates a variable called result and calculates the result by adding the four numbers, and then dividing by 4. (The parentheses are necessary to tell JavaScript to perform the addition before the division.)

To send this result back to the script that called the function, you use the return keyword. Here is the last part of the function:

return result;
}

Listing 6.3 shows the complete Average() function in an HTML document. This HTML document also includes a small script in the <body> section that calls the Average() function and displays the result.

Listing 6.3. The Average() Function in an HTML Document

<html>_
<head>
<title>Function Example</title>
<script language="JavaScript" type="text/javascript">
function Average(a,b,c,d) {
result = (a + b + c + d) / 4;
return result;
}
</script>
</head>
<body>
<p>The following is the result of the function call.</p>
<script LANGUAGE="JavaScript" type="text/javascript">
score = Average(3,4,5,6);
document.write("The average is: " + score);
</script>_
</body>
</html>

You can use a variable with the function call, as shown in this listing. This statement averages the numbers 3, 4, 5, and 6 and stores the result in a variable called score:

score = Average(3,4,5,6);

Did you Know?

You can also use the function call directly in an expression. For example, you could use the alert statement to display the result of the function: alert(Average(1,2,3,4)).


Previous Page
Next Page
Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


     Main Menu
Sams Teach Yourself JavaScript in 24 Hours
Table of Contents
Copyright
About the Author
Acknowledgments
Part I: Introducing the Concept of Web scripting and the JavaScript Language
Part II: Learning JavaScript Basics
Hour 5. Using Variables, Strings, and Arrays
Hour 6. Using Functions and Objects
Using Functions
Introducing Objects
Using Objects to Simplify Scripting
Extending Built-in Objects
Summary
Q&A
Quiz Questions
Quiz Answers
Exercises
Hour 7. Controlling Flow with Conditions and Loops
Hour 8. Using Built-in Functions and Libraries
Part III: Learning More About the DOM
Part IV: Working with Advanced JavaScript Features
Part V: Building Multimedia Applications with JavaScript
Part VI: Creating Complex Scripts
Part VII: Appendixes
Index


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele