Hour 3

Using Functions

What You’ll Learn in This Hour

  • How to define functions
  • How to call (execute) functions
  • How functions receive data
  • Returning values from functions
  • About the scope of variables

Commonly, programs carry out the same or similar tasks repeatedly during the course of their execution. For you to avoid rewriting the same piece of code over and over again, JavaScript has the means to parcel up parts of your code into reusable modules, called functions. After you’ve written a function, it is available for the rest of your program to use, as if it were itself a part of the JavaScript language.

Using functions also makes your code easier to debug and maintain. Suppose you’ve written an application to calculate shipping costs; when the tax rates or haulage prices change, you’ll need to make changes to your script. There may be 50 places in your code where such calculations are carried out. When you attempt to change every calculation, you’re likely to miss some instances or introduce errors. However, if all such calculations are wrapped up in a few functions used throughout the application, then you just need to make changes to those functions. Your changes will automatically be applied all through the application.

Functions are one of the basic building blocks of JavaScript and will appear in virtually every script you write. In this hour you see how to create and use functions.

General Syntax

Creating a function is similar to creating a new JavaScript command that you can use in your script.

Here’s the basic syntax for creating a function:

function sayHello() {
    alert("Hello");
    // ... more statements can go here ...
}

You begin with the keyword function, followed by your chosen function name with parentheses appended, then a pair of curly braces {}. Inside the braces go the JavaScript statements that make up the function. In the case of the preceding example, we simply have one line of code to pop up an alert dialog, but you can add as many lines of code as are necessary to make the function...well, function!

Caution

The keyword function must always be used in lowercase, or an error will be generated.

To keep things tidy, you can collect together as many functions as you like into one <script> element:

<script>
    function doThis() {
        alert("Doing This");
    }
    function doThat() {
        alert("Doing That");
    }
</script>

Calling Functions

Code wrapped up in a function definition will not be executed when the page loads. Instead, it waits quietly until the function is called.

To call a function, you simply use the function name (with the parentheses) wherever you want to execute the statements contained in the function:

sayHello();

Tip

Function names, like variable names, are case-sensitive. A function called MyFunc() is different from another called myFunc(). Also, as with variable names, it’s really helpful to the readability of your code to choose meaningful function names.

For example, you may want to add a call to your new function sayHello() to the onClick event of a button:

<input type="button" value="Say Hello" onclick="sayHello()" />

Tip

You’ve already seen numerous examples of using the methods associated with JavaScript objects, such as document.write() and window.alert().

Methods are simply functions that “belong” to a specific object. You learn much more about objects in Hour 4, “DOM Objects and Built-In Objects.”

Putting JavaScript Code in the Page <head>

Up to now, our examples have all placed the JavaScript code into the <body> part of the HTML page. Using functions lets you employ the much more common, and usually preferable, practice of storing our JavaScript code in the <head> of the page. Functions contained within a <script> element in the page head, or in an external file included via the src attribute of a <script> element in the page head, are available to be called from anywhere on the page. Putting functions in the document’s head section ensures that they have been defined prior to any attempt being made to execute them.

Listing 3.1 has an example.











Listing 3.1. Functions in the Page Head

In this listing, you can see that the function definition itself has been placed inside a <script> element in the page head, but the call to the function has been made from a different place entirely—on this occasion, from the onClick event handler of a button in the body section of the page.

The result of clicking the button is shown in Figure 3.1.

Image

Figure 3.1. Calling a JavaScript function

Arguments

It would be rather limiting if your functions could only behave in an identical fashion each and every time they were called, as would be the case in the preceding example.

Fortunately, you can extend the capabilities of functions a great deal by passing data to them. You do this when the function is called, by passing to it one or more arguments:

functionName(arguments)

Let’s write a simple function to calculate the cube of a number and display the result:

function cube(x) {
    alert(x * x * x);
}

Now we can call our function, replacing the variable x with a number. Calling the function like this

Note

You’ll sometimes see or hear the word parameters used in place of arguments, but it means exactly the same thing.

cube(3);

results in a dialog box being displayed that contains the result of the calculation, in this case 27.

Caution

Make sure that your function calls contain enough argument values to match the arguments specified in the function definition. If any of the arguments in the definition are left without a value, JavaScript may issue an error, or the function may perform incorrectly. If your function call is issued with too many arguments, the extra ones will be ignored by JavaScript.

Of course, you could equally pass a variable name as an argument. The following code would also generate a dialog containing the number 27:

var length = 3;
cube(length);

Multiple Arguments

Functions are not limited to a single argument. When you want to send multiple arguments to a function, all you need to do is separate them with commas:

function times(a, b) {
    alert(a * b);
}
times(3, 4); // alerts '12'

You can use as many arguments as you want.

It’s important to note that the names given to arguments in the definition of your function have nothing to do with the names of any variables whose values are passed to the function. The variable names in the argument list act like placeholders for the actual values that will be passed when the function is called. The names that you give to arguments are only used inside the function definition to specify how it works.

We talk about this in more detail later in the hour when we discuss variable scope.

Video 3.1—Try It Yourself: A Function to Output User Messages

Let’s use what we’ve learned so far in this hour by creating a function that can send the user a message about a button he or she has just clicked. We place the function definition in the <head> section of the page and call it with multiple arguments.

Here’s our function:

function buttonReport(buttonId, buttonName, buttonValue) {
    // information about the id of the button
    var userMessage1 = "Button id: " + buttonId + "\n";
    // then about the button name
    var userMessage2 = "Button name: " + buttonName + "\n";
    // and the button value
    var userMessage3 = "Button value: " + buttonValue;
    // alert the user
    alert(userMessage1 + userMessage2 + userMessage3);
}

Tip

You may have noticed that the first two message strings have an element "\n" appended to the string; this is a “new line” character, forcing the message within the alert dialog to return to the left and begin a new line. Certain special characters like this one must be prefixed with \ if they are to be correctly interpreted when they appear in a string. Such a prefixed character is known as an escape sequence. You learn more about escape sequences in Hour 5, “Different Types of Data.”

The function buttonReport takes three arguments, those being the id, name, and value of the button element that has been clicked. With each of these three pieces of information, a short message is constructed. These three messages are then concatenated into a single string, which is passed to the alert() method to pop open a dialog containing the information.

To call our function, we put a button element on our HTML page, with its id, name, and value defined:

<input type="button" id="id1" name="Button 1" value="Something" />

We need to add an onClick event handler to this button from which to call our function. We’re going to use the this keyword, as discussed in Hour 2, “Writing Simple Scripts”:

onclick = "buttonReport(this.id, this.name, this.value)"

The complete listing is shown in Listing 3.2.

Listing 3.2. Calling a Function with Multiple Arguments

Use your editor to create a file buttons.html and enter the preceding code. You should find that it generates output messages like the one shown in Figure 3.2, but with different message content depending on which button has been clicked.

Image

Figure 3.2. Using a function to send messages

Note

The values returned by functions are not restricted to numerical quantities as in this example. In fact, functions can return values having any of the data types supported by JavaScript. We discuss data types in Hour 5.

Returning Values from Functions

Okay, now you know how to pass information to functions so that they can act on that information for you. But how can you get information back from your function? You won’t always want your functions to be limited to popping open a dialog box!

Luckily, there is a mechanism to collect data from a function call—the return value. Let’s see how it works:

function cube(x) {
    return x * x * x;
}

Instead of using an alert() dialog within the function, as in the previous example, this time we prefixed our required result with the return keyword. To access this value from outside the function, we simply assign to a variable the value returned by the function:

var answer = cube(3);

The variable answer will now contain the value 27.

Tip

Where a function returns a value, we can use the function call to pass the return value directly to another statement in our code. For example, instead of

var answer = cube(3);
alert(answer);

we could simply use

alert(cube(3));

The value of 27 returned from the function call cube(3) immediately becomes the argument passed to the alert() method.

Scope of Variables

We have already seen how to declare variables with the var keyword. There is a golden rule to remember when using functions:

“Variables declared inside a function only exist inside that function.”

This limitation is known as the scope of the variable. Let’s see an example:

// Define our function addTax()
function addTax(subtotal, taxRate) {
    var total = subtotal * (1 + (taxRate/100));
    return total;
}
// now let's call the function
var invoiceValue = addTax(50, 10);
alert(invoiceValue); // works correctly
alert(total);  // doesn't work

If we run this code, we first see an alert() dialog with the value of the variable invoiceValue (which should be 55 but in fact will probably be something like 55.000000001 as we have not asked JavaScript to round the result).

We will not, however, then see an alert() dialog containing the value of the variable total. Instead, JavaScript simply produces an error. Whether you see this error reported depends on your browser settings—we learn more about error handling later in the book—but JavaScript will be unable to display an alert() dialog with the value of your variable total.

This is because we placed the declaration of the variable total inside the addTax() function. Outside the function the variable total simply doesn’t exist (or, as JavaScript puts it, “is not defined”). We used the return keyword to pass back just the value stored in the variable total, and that value we then stored in another variable, invoice.

We refer to variables declared inside a function definition as being local variables, that is, local to that function. Variables declared outside any function are known as global variables. To add a little more confusion, local and global variables can have the same name, but still be different variables!

The range of situations where a variable is defined is known as the scope of the variable—we can refer to a variable as having local scope or global scope.

Video 3.2—Try It Yourself: Demonstrating the Scope of Variables

To illustrate the issue of a variable’s scope, take a look at the following piece of code:

var a = 10;
var b = 10;
function showVars() {
    var a = 20; // declare a new local variable 'a'
    b = 20;     // change the value of global variable 'b'
    return "Local variable 'a' = " + a + "\nGlobal variable 'b' = " + b;
}
var message = showVars();
alert(message + "\nGlobal variable 'a' = " + a);

Within the showVars() function we manipulate two variables, a and b. The variable a we define inside the function; this is a local variable that only exists inside the function, quite separate from the global variable (also called a) that we declare at the very beginning of the script.

The variable b is not declared inside the function, but outside; it is a global variable.

Listing 3.3 shows the preceding code within an HTML page.

Listing 3.3. Global and Local Scope

When the page is loaded, showVars() returns a message string containing information about the updated values of the two variables a and b, as they exist inside the function—a with local scope, and b with global scope.

A message about the current value of the other, global variable a is then appended to the message, and the message displayed to the user.

Copy the code into a file scope.html and load it into your browser. Compare your results with Figure 3.3.

Image

Figure 3.3. Local and global scope

Summary

In this hour you learned about what functions are and how to create them in JavaScript. You learned how to call functions from within your code and pass information to those functions in the form of arguments. You also found out how to return information from a function to its calling statement.

Finally, you learned about the local or global scope of a variable and how the scope of variables affects how functions work with them.

Q&A

Q. Can one function contain a call to another function?

A. Most definitely; in fact, such calls can be nested as deeply as you need them to be.

Q. What characters can I use in function names?

A. Function names must start with a letter or an underscore and can contain letters, digits, and underscores in any combination. They cannot contain spaces, punctuation, or other special characters.

Quiz

Quiz Loads Here

 

 

 

Exercises

Write a function to take a temperature value in Celsius as an argument and return the equivalent temperature in Fahrenheit, basing it on the code from Hour 2.

Test your function in an HTML page.