Chapter 7. Working with Functions

After reading this chapter, you'll be able to

  • Understand the purpose of functions in JavaScript.

  • Define your own functions.

  • Call functions and receive data back from them.

  • Understand some of the built-in functions in JavaScript.

What's in a Function?

A JavaScript function is a collection of statements, either named or unnamed, that can be called from elsewhere within a JavaScript program. Functions can accept arguments or input values that are passed into the function. Within a function, those arguments passed into the function can be acted upon and then passed back out of the function through a return value.

Functions are perfect for when you have something that needs to happen multiple times within a program. Rather than defining the same code multiple times on the page, you can use a function (which is really just like a mini-program inside a program) to perform that action. Even if you have bits of code that are very similar—but not identical—throughout the program, you might be able to abstract them into a single function.

A good example of abstracting similar code is a function to verify that required form fields have been filled in. You can write JavaScript code to verify each individual named field in the form, or you could use a function. Chapter 11, will show an example of building a specific function and then showing how to abstract it.

You've already seen functions at work through examples in earlier chapters. A function is defined with the keyword function, usually followed by the name of the function and then parentheses with optional arguments or parameters to be used within it. Use braces to hold the statements to be executed as part of the function:

function functionName() {
    // Statements go here;
}

Tip

When a function is defined, as you see with this basic function definition, it's important to note that the code isn't actually executed until the function is invoked or called. You'll see how to call a function shortly.

Function Arguments

Arguments passed to a function go within the parentheses of the function definition. Here's a brief example of a function argument:

function myFunction(argument1, argument2) {
    // Do something with argument1 and argument 2 in the code
}

Calling or invoking the function is as simple as:

myFunction(val1,val2);

When invoked, the function is given an array simply called arguments, which holds the arguments sent into the array. This can be helpful when you don't know the number of arguments being sent in. Here's an example:

function myFunction() {
    var firstArg = arguments[0];
    var secondArg = arguments[1];
}

Better still, you could get the length of the arguments array and loop through each, as follows:

function myFunction() {
    for (var i = 0; i < arguments.length; i++) {
        // Do something with each argument (i)
    }
}

Here's a fuller example showing the results from a simple use of the arguments array:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>Arguments Array</title>
</head>
<body>
<script type="text/javascript">
function myFunction() {
    var firstArg = arguments[0];
    var secondArg = arguments[1];
    alert("firstArg is: " + firstArg);
    alert("secondArg is: " + secondArg);
}
myFunction("hello","world");
</script>
</body>
</html>

When the code executes, it displays two alerts, as depicted in Figures Figure 7-1 and Figure 7-2.

Using the arguments array within a function to access the first argument

Figure 7-1. Using the arguments array within a function to access the first argument

Using the arguments array within a function to access the second argument

Figure 7-2. Using the arguments array within a function to access the second argument

Obviously, using the arguments array in this way can be extrapolated to any number of arguments, not just the two shown here.

Variable Scoping Revisited

Function arguments are frequently variable names and shouldn't be named the same as the variables that are used to call or invoke the function. I use the purposefully vague conjunction "shouldn't" here because there's really no reason why you couldn't name the variables the same within the function as they're named in the function invocation, other than it can create some confusing code and confusing scoping, as you'll see.

Chapter 4, contained a section on variable scoping, including an exercise dealing with scoping inside and outside functions. The relevant code from one of the variable scoping examples in Chapter 4 looked like this:

<head>
    <title>Scoping Example</title>
    <script type = "text/javascript" >
    var aNewVariable = "is global.";
    function doSomething(incomingBits) {
        alert("Global variable within the function: " + aNewVariable);
        alert("Local variable within the function: " + incomingBits);
    }

    </script>

</head>
<body>
<script type = "text/javascript" >

    doSomething("is a local variable");
    alert("Global var outside the function: " + aNewVariable);
    alert("Local var outside the function: " + incomingBits);

</script>
</body>

This example showed how globally and locally declared and scoped variables are seen from inside and outside a function. However, it kept the variables logically separate, in that the example didn't use the same variable name and then change its value. Here's an example where using the same variable name might cause confusion. I've found that code I wrote years ago is confusing enough without introducing weird scoping issues, so try to avoid code like this:

function addNumbers() {
    firstNum = 4;
    secondNum = 8;
    result = firstNum + secondNum;
    return result;
}
result = 0;
sum = addNumbers();

You might have already spotted the problem with this code. The var keyword is missing pretty much everywhere. Even though the code explicitly initializes the result variable to 0 outside the function, the variable gets modified by the call to the addNumbers() function. This in turn modifies the result variable, making it 12, the result of adding 4 and 8 inside the function.

If you were to add an alert to display the result variable right after the initialization of the result variable, it would show 0. And if you added another alert to display the result variable after the call to the addNumbers() function, it now would show 12. I'll leave it to you as an exercise later to add these alerts in the right places.

The bottom line is that your life will be easier if you use different names for variables inside and outside functions and always use the var keyword to initialize variables. Depending on the code contained in the function, it may or may not have a return value. That return value is passed back to the caller, as you'll see in the next section.

Return Values

When a function finishes executing its code, a return value can be passed back to the caller. Take a look at Example 7-1.

Example 7-1. A Simple return Value Example

function multiplyNums(x) {
    return x * 2;
}
var theNumber = 10;
var result = multiplyNums(theNumber);
alert(result);

In Example 7-1, a function, multiplyNums is created with an intended input value, which will be set to the variable x. The function does one thing—return its argument multiplied by 2, as follows:

function multiplyNums(x) {
    return x * 2;
}

The code then creates a variable called theNumber, as follows:

var theNumber = 10;

Next, the code creates another variable called result. This variable will hold the result of the call to the multiplyNums function. The multiplyNum function uses the variable theNumber as an argument:

var result = multiplyNums(theNumber);

When run, the code results in a dialog box, like the one shown in Figure 7-3.

This alert shows the return value from the function call

Figure 7-3. This alert shows the return value from the function call

Actually, the return value can be placed anywhere within a function, not just at the end. It's common to use a return within a conditional or after a loop, like this:

function myFunction(x) {
    if (x == 1) {
        return true;
    } else {
        return false;
}

Be careful where you place the return statement, though. Once the function hits the return statement, it jumps out and won't execute any code after that. Code like this probably won't do what you want:

function myFunction() {
    var count = 0;
    var firstNum = 48;
    return;
    var secondNum = 109;
}

This code will never get to the initialization of the variable secondNum.

More on Calling Functions

When you call or invoke a function, you'll usually call it with some arguments or at least with empty parentheses, like this:

var result = orderFruit();

If arguments are required for that function, it might look like this:

var result = orderFruit(type,quantity);

Omitting the parentheses to call a function may result in actions that are entirely different from what you want. Calling a function without parentheses results in the text of the function being returned, rather than whatever the function was supposed to return. Just as important, the function isn't actually executed.

Here's an example. Example 7-2 shows some basic JavaScript code.

Example 7-2. Invoking a Function

<!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>Order Fruit</title>
    <script type = "text/javascript">
    function orderFruit() {
        var total = 0;
        // Call another function to place order 
        return total;
    }
    </script>
</head>
<body>
<script type = "text/javascript">
var result = orderFruit();
alert("The total is " + result);
</script>
</body>
</html>

When executed, this code will invoke the orderFruit() function. The orderFruit() function actually invokes another function (not shown) to place an order. The total is then calculated and sent back to the caller. As written, the code will work fine, resulting in a dialog box like that shown in Figure 7-4.

Invoking the orderFruit() function with parentheses yields the results you'd expect

Figure 7-4. Invoking the orderFruit() function with parentheses yields the results you'd expect

A slight modification to the code, specifically changing the function call to remove the parentheses, changes the entire result:

var result = orderFruit;

The result is shown in Figure 7-5.

Calling orderFruit without parentheses probably doesn't turn out the way you'd want

Figure 7-5. Calling orderFruit without parentheses probably doesn't turn out the way you'd want

Whether or not a function returns a value or accepts any arguments, it's important to call it using parentheses to actually execute the function's code.

Unnamed Functions (Function Literals)

Functions don't have to be as formally delineated as you've seen in the examples so far in this chapter and throughout the rest of this book. Function literals are beyond the scope of this text, so I won't cover them other than giving a brief definition. With a function literal, also known as an unnamed function, the function itself is defined and tied to a variable, like this:

var divNums = function(firstNum,secondNum) { return firstNum / secondNum; };

Methods

The easiest way to think about methods is that methods are functions defined as part of an object. It's a bit of an oversimplification, but it'll do for now. You access a method of an object through the dot operator ("."). Built-in objects, such as the Math, Date, and String objects, all have methods that you've seen or will soon see in this book. Things like the alert() function are actually just methods of the window object and could also be written window.alert() rather than just alert().

Note

For much of the book, I've used the term method and function rather interchangeably. I'll continue to do so just to give you a better understanding that the line between these two is rather unspecific for most uses. When a function is used in an object-oriented manner, it's better or clearer to use the term method. When not used directly in an object-oriented manner, however, as with the alert() function, it's okay to call it a function.

Chapter 8, covers objects and methods in greater detail.

A Look at Dialog Functions

By now, you know all about the alert() function in JavaScript because you've seen many examples of it in previous chapters. You've also learned that the alert() function is just a method of the window object. This section looks at the everyday use of the alert() function in JavaScript, as well as two related functions of the window object.

Note

More Info The window object is important enough to get some additional attention in Chapter 9. We'll discuss the numerous methods of the window object in that chapter.

Although the window object has several methods, for now, I'd just like to highlight these three functions (which are technically methods): alert(), confirm(), and prompt(). Because you've already seen too many alert() dialog boxes in the book, I won't include another one here (thank me later). Chapter 6, discussed the use of the prompt() function and the fact that as of Microsoft Windows Internet Explorer 7, the prompt() function is now blocked by default as a security measure. The confirm() function is still available in Windows Internet Explorer, though.

The confirm() function displays a modal dialog box with two buttons, OK and Cancel, like the one shown in Figure 7-6. (A modal dialog box prevents other activity or clicks in the browser until the visitor clicks OK or Cancel.)

The confirm() function provides a dialog box for making decisions with JavaScript

Figure 7-6. The confirm() function provides a dialog box for making decisions with JavaScript

If you click OK, the confirm() function returns true. On the other hand, as you might guess, if you click Cancel, the confirm() function returns false.

Like alert() and prompt(), the confirm() function creates a modal dialog box on most platforms. This can get annoying if these functions are overused or used in the wrong place. But used properly, to provide important feedback and obtain vital information, these functions can be quite useful.

Tip

Don't use the confirm() function in place of a Web form to obtain user input. The Web form is much better for navigation and will keep your visitors happier.

The next step-by-step exercise will walk you through using the confirm() function to obtain input and make a decision.

Obtaining input with confirm()

  1. Using Microsoft Visual Studio, Eclipse, or another editor, edit the file confirm.htm in the Chapter 7 sample files folder.

  2. Within the page, add the code shown below in bold type:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
        <title>Confirming Something</title>
    
        <script type = "text/javascript">
    
        function processConfirm(answer) {
            var result = "";
            if (answer) {
                result = "Excellent. We'll play a nice game of chess.";
            } else {
                result = "Maybe later then.";
            }
            return result;
        }
        </script>
    </head>
    <body>
    <script type = "text/javascript">
    
    var confirmAnswer = confirm("Shall we play a game?");
    var theAnswer = processConfirm(confirmAnswer);
    alert(theAnswer);
    </script>
    </body>
    </html>
  3. Save the page and view it in a Web browser. You'll be presented with a dialog box like this:

    image with no caption
  4. Click OK. You'll then see an alert() dialog box, like this:

    image with no caption
  5. Click OK, and then reload the page.

  6. You'll once again be shown the original dialog box from the confirm() function, asking if you'd like to play a game. This time click Cancel. You'll be presented with a different alert() dialog box:

    image with no caption
  7. Click OK to clear the dialog box.

The code has two major areas, one within the <head> and the other within the <body>. Within the <head> portion of the page, the function processConfirm(answer) is created:

function processConfirm(answer) {
    var result = "";
    if (answer) {
        result = "Excellent. We'll play a nice game of chess";
        } else {
            result = "Maybe later then.";
        }
        return result;
    }

This function evaluates the value contained in the argument that is held in the variable answer. If the value in the answer variable evaluates to true, as it does if the visitor clicks OK, then the function creates the variable result and assigns to result a string value of "Excellent. We'll play a nice game of chess." On the other hand, if the value in the answer variable evaluates to false, as it does if the visitor clicks Cancel, then the function still creates the result variable, but now assigns to this variable the value of "Maybe later then." Regardless of what's held in the answer variable, the result variable is sent back to the caller by the return statement within the function. The function could be more succinctly written like so:

function processConfirm(answer) {
    if (answer) {
        return "Excellent. We'll play a nice game of chess.";
    } else {
        return "Maybe later then.";
    }
}

And even more succinctly:

function processConfirm(answer) {
    var result;
    (answer) ? result = "Excellent. We'll play a nice game of chess." : result = "Maybe
later then.";
    return result;
}

In all likelihood, I would use the last function example to perform this task. However, I've found many a programmer who isn't comfortable with the ternary logic of the last example and so for readability, I'd choose the more explicit of the two:

function processConfirm(answer) {
    if (answer) {
        return "Excellent. We'll play a nice game of chess.";
    } else {
        return "Maybe later then.";
    }
}

The JavaScript contained within the <body> section of the code creates the confirm dialog box, calls the processConfirm() function, and displays the result:

var confirmAnswer = confirm("Shall we play a game?");
var theAnswer = processConfirm(confirmAnswer);
alert(theAnswer);

Like the alert() function, the confirm() function accepts a single argument, which is the message to be displayed within the dialog box. Unlike the alert() function, with the confirm() function it's best to phrase your prompt in the form of a question or other statement that gives the visitor a choice. If the user really doesn't have a choice, then use the alert() function instead. An even more succinct version would combine all three lines, like this:

alert(processConfirm(confirm("Shall we play a game?")));

Exercises

  1. Define a function that takes one numeric argument, increments that argument, and then returns it to the caller. Call the function from within the <body> of a page and display the result on the screen.

  2. Define a function that accepts two numeric parameters. If the value of the first parameter is greater than the second, show an alert to the visitor. If the value of the first parameter is less than or equal to the second, return the sum of both parameters.

  3. Add appropriate alert() functions to the following code so that you can see the value in the result variable both before and after the function call. Here's the code:

    function addNumbers() {
        firstNum = 4;
        secondNum = 8;
        result = firstNum + secondNum;
        return result;
    }
    result = 0;
    sum = addNumbers();
  4. Create an array with seven string values, initialized to the names of these stars: Polaris, Aldebaran, Deneb, Vega, Altair, Dubhe, and Regulus. Create an array with seven additional string values, initialized to the names of the constellations in which the stars are found: Ursa Minor, Taurus, Cygnus, Lyra, Aquila, Ursa Major, and Leo. Next, create a function that accepts a single string parameter. Within the function, iterate through the first array searching for the star. When the star is found, return the value contained in that index within the second array. In other words, return the constellation name for that star. Within the <body> of the page, use a prompt to gather the name of the star from the visitor and then call the function with that input. Don't forget to include code if the star isn't found. Display the result on the screen.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.193.232