Hour 3
Using Functions
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.
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.
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.
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.