Chapter 8
Conjunction Junction, What's a Function?

In This Chapter

If statements are the connective tissue of a JavaScript program, and functions are the blood. (See, that high school anatomy course really has paid off.) Any JavaScript program beyond the most basic is going to include functions. Some are built into JavaScript (those are listed in Appendix A at the end of this book); however, you will create other functions.

That's great, and very nice to know, but what is a function? A very apropos question. Could you ask it again, and this time a little louder?

What Is a Function?

Much better. A function is like a miniprogram unto itself. It can be "called" from the rest of the JavaScript program. A function is composed of JavaScript code, which, if executed, accomplishes some task. The set of code composing the function is given a name or label of some sort. That name then comes to represent a particular function, or set of code. Creating a function is not the same as calling a function. In this chapter, you will see how a function is "defined" (that is, how you write out the code that belongs to the labeled function). When it is executed, a function is called from some other section of JavaScript code. You will see how this is done, as well.

[ic:check]Calling All Functions! When you "call" a function, you are instructing JavaScript to execute that 
function. Remember that a function is a miniprogram of JavaScript code. So "calling" it means to execute the
code that comprises a particular function.

You often use a function to define a procedure that will be called upon regularly. By doing so, you program and name a set routine so you can call it repeatedly without having to redefine it over and over. To make an analogy to real life, throughout the day you have many functions in your daily activities. You might consider sleep a function. Likewise, eating lunch is a function. Between these predefined activities, you act out other tasks, which are sometimes similar to loops and conditional statements.

For example, perhaps you are watching television. While doing so, certain conditions may occur: if hungry; if sleepy; if bladder full. These are like conditional statements in a JavaScript program. Upon evaluation of these conditions, you may choose to call upon a predefined function. For example, if hungry, eat lunch; if bladder full, run to bathroom. In each case, eat lunch and run to bathroom are functions because they refer to a defined series of actions. That series, however, must have been defined only once sometime in the past. For instance, the function "run to bathroom" may have been "defined" when you were toilet-trained. Since then, you have simply called that function to execute it when necessary. A vivid image, no doubt.

So far in the statements you have used in this book, you have called upon only very simple actions. Soon you will learn how to create and define functions—whole sets of actions that can vary in size from one statement to a whole other program in and of itself—which can then be called from statements.

The Role of Parameters

Functions frequently, although not necessarily, accept parameters when they are called. A parameter is a specified value that somehow plays a role in the doings of the function's actions. Let's recall the lunch function from real life. Although the procedure for eating lunch is predefined, there are a few variables you do need to take note of. The most obvious being, what food will you be eating for lunch? What beverage will accompany this food?

[ic:check]Function Notation You specify the variables included in a function by listing them within 
parentheses beside the function name. An example might be lunch (food,beverage). It is common practice,
in a book such as this, to write a function name in the format lunch(). This simply means that you're speaking 
of the function named lunch, although you're not considering its particular variables at this time.

In this sense, you can say that the function lunch() takes two parameters: foodstuff and beverage. When you feel peckish just around noon, you call your lunch function with these two parameters, which you could note in the following way:

In this example, you invoke your lunch() function with the specifics of a pizza and a Coke. Similarly, functions in JavaScript can also take parameters. When you define the function (which you will do shortly), you must decide which parameters the function will require. When you define a function, you don't know what the specific parameter values will be. That is determined when you call the function, somewhere else in the JavaScript program. When you define the function lunch(), you might name the parameters foodstuff and beverage, for instance. Only when you later call the function lunch() will you use actual values for these parameters.

Returned Results

At the conclusion of a function, you will often (but not always) want to return some sort of result to the program. Again, with the lunch example, you might say that the function lunch() accepts two parameters, foodstuff and beverage, and returns one result: a variable called satisfaction, which will contain a logical value true or false.

By this logic, the lunch() function processes the foodstuff and beverage specified to it ("pizza" and "Coke" in this case) and then returns a true or a false value for the variable satisfaction. The calling program (in this example, that would be you, the person) then examines this result and decides what to do from there. It may choose to call the function again with new parameters (for example, if satisfaction was returned as false, you might want to run for more food), or it may choose to move on with the remainder of the program (if satisfaction is returned as true, for example).

Now I'm Hungry: Defining and Calling a Function

The formal template for a function definition looks like this:

Therefore, the formal JavaScript definition for the lunch() function would have looked like this:

Of course, the statements within brackets in this example are all fake, because there are no real JavaScript statements that define eating food. Remember that the above function is not executed unless it is called from somewhere else in the JavaScript program. Merely defining it does not execute it.

In addition, let me pass along an important word about parameters that I briefly touched upon earlier. When you name parameters in the function definition, you are essentially creating variables. Whatever values are passed to the function in the function call, will be assigned to the variables you have named in the function definition (in the order that they are listed in the function call). So if you called the previous function with the following call:

lunch("pizza", "Coke");

Within the statements of the function lunch(), the variable foodstuff will contain the string value "pizza", and the variable beverage will contain the string value "Coke". In this function call, you have passed literals as the parameter values. Alternatively, if you call the function with this statement,

the variable foodstuff will contain the value of the variable choice1; likewise, beverage will contain the value of the variable choice2. In this function call, you have passed the contents of variables as parameter values.

Would You Like Parameters with That Function?

A function does not have to accept any parameters. The one you are writing may not need any. In these 
cases, you simply continue to use the () where they are required (in the function definition and function calls),
but you put nothing in between, as in these examples:

More About Function Calls

You'll see several function calls in action in later examples. For now, however, you should get a grasp on the two forms of function calls. You have just seen one common form: the plain function call. It exists, as written, in the following form:

functionname(parameter1, ...);

However, recall the role of the "return" value. In the lunch() example, after the function completes (the meal has been consumed), the function returns the value of the variable satisfaction, which is a logical value of true or false. Where is this value returned to? Mid-air? In the plain function calls above, the value is not returned anywhere. It has nowhere to go. To make a function call that can accept a returned value, you make the call within an assignment. For example:

morefood = lunch("pizza", "Coke");

In this case, the function lunch() will be called, and the food will be processed just as in the plain function call. In addition, though, the logical value that is returned from the function will be assigned to the variable morefood. From there, you might use morefood in future conditional evaluations later in the program.

Therefore, for the calling program to accept a return value from a function, the call is made in the form

variableforreturn = functionname(parameter1, ...);

Let's Make a Function!

Now you're ready to define a real JavaScript function. No more talk about lunch. You will build on an example that was already coded in the previous chapter. In Chapter 7, you wrote a small segment of JavaScript code that calculated the daily gross profit on product purchases via a Web page. The special exception was that every 10th purchase was free, so for every 10th purchase, a zero was added to your cumulative total.

Now let’s turn that segment into an official function. The task: Calculate daily gross profit, leaving every 10th purchase out of the total. Return total gross.

To do that, you first define the function, which will be called promotion():

function promotion(orders, price) {

As you can see, you are sending two parameters to the function: orders, which represents the total number of orders for the day, and price, which is an object for which each property is a price of sale for a given order.

Note that price is an object, which must have been created prior to calling the function; however, you have not yet learned how to create an object because doing so is a variation on creating functions. For now, assume the object price was created elsewhere in the JavaScript program. By the end of this chapter, you'll know how to create objects for real.

Finally, write the { statements } section of the function.

var total = 0;
for (var count = 1; count <= orders; count++) {
if (( count % 10 ) == 0 ) {
total += price[count];
return total

For the most part, the example above is the same as the example code for the continue statement that was used in Chapter 7. There are a couple of differences to note:

[ic:check]Motherly Advice

It’s because of this “special case” var situation that you’re encouraged to always use a var statement when
assigning values to variables. Doing so would prevent any possible mistakes that might occur if you forgot 
to use a var statement when it really was necessary. Ultimately, the choice is yours. If you trust yourself to 
remember to use var statements within functions, you may opt to forego them elsewhere. On the other 
hand, if you tend to forget where you put your pen down five seconds ago, perhaps the recommended 
var usage is the way to go.

The Whole Burrito: A Finished Function

For the purposes of science and education, in the previous example, you sort of decapitated the function definition from the entire function body. Now you'll rejoin the two parts and wind up with one fully mature, living, working function.

Because this function's entire purpose in life is to calculate and return a value, you want to call it in an assignment. So, wherever it is in your JavaScript program that you want to execute this function and use its result, you would call it with an expression such as:

total = promotion(orders, price);

Although you needn't call the function with variable names that match the parameter names, in this case, you have done so simply because the variable names are equally sensible labels in both portions of the program.

Making the Call

You can make a function call in any valid location for a statement. For example, you might include a function call in an if...else statement, as in

if (hunger == true) {
morefood = lunch("pizza", "Coke");
} else {

Here, the fictitious function lunch() is called if the hunger condition is true, and the equally fictitious function watchtv is called if the hunger condition is false.

Also note that a function can call another function in the course of its { statements }. However, there is an important rule (which you’ll see again in a later chapter) that a function must have been defined before any calls are made to it. Therefore, if you are calling one function from another, the function being called has to have been defined previously in the JavaScript program (before the definition of the function making the call).

Top Loading
 Because functions must be defined before they can be called, the best way to avoid potential problems is to simply place all function definitions at the top of your JavaScript program, above any other programming. Some people recommend placing all of the function definitions at the very top of the Web page between the <HEAD> and </HEAD> tags so they will always be loaded before anything else. (You'll see an example of that in a later chapter.)

Even more interesting, a function can be passed as a parameter to another function. This makes sense if you think about it. Consider the promotion() function defined earlier. It returns a result of the gross profit for the day. Suppose you have another function, weekly, which performs a weekly gross summary and takes two parameters: total sales for the week (wkorders) and gross daily profit for the current day (the promotion() function). It returns the value for current gross weekly sales. One might then call weekly with the statement

Method Programming

Supposedly, Marlon Brando was a classic method actor. Of course, he was largely before my time (and I stress "largely"), but there are methods in JavaScript programming as well. Follow this closely: In JavaScript, a method is a function that is a property of an object.

Thus far, you have seen one type of object property: the common garden-variety variable. An example was


However, it is possible for the property—and not the variable—to be a function. Thus, imagine you have a function that calculates the price of a sweater based on other characteristics, such as its material. The function itself doesn't matter now. You'll just assume that the function fprice() has been defined and takes the parameter material. It is assigned to the object property price. Now your whole sweater object looks like this:


The first three properties are variables and may be assigned values (as in the first example below) or may be assigned to other variables (as in the second example):

sweater.material = "argyle";
buystock = sweater.material;

However, the fourth property is a method—a function within the object. Therefore, assigning a value to it is nonsensical. Instead, it is something that you call. For instance, you might call the method sweater.price() and assign the returned result to some other variable, as in this example:

total += sweater.price();

That's really all there is to a method. It is a function just like those discussed throughout this chapter; the only difference is that it exists as a property of an object instead of "on its own." 

Methods are created when an object is created. You haven't yet learned how to create an object, and doing so is the only remaining building block you need to know for writing full-fledged JavaScript programs. Therefore, Que proudly presents...the creation process.

Object Creationism

An object is, truth be told, a function. To use an object such as sweater in your program, you first need to define its function. That provides the structure for the object.

The function, in this case, takes parameters that represent each property. But, as you'll repeat, the function merely defines the structure of the object; it does not create the object itself. Thus, although you are ultimately interested in creating a sweater object, its definition needn't be called sweater. Imagine, for example, that you sell several sorts of topwear, such as sweaters, T-shirts, and tank tops. All of these may be defined by the same object definition. Later, however, you'll create separate objects to represent each. Let’s do this by example.

For your first example, define a topwear object that does not contain a method. Instead, it contains three regular variable properties: material, color, and size. Succeeding the function definition, watch the { statements } section.

function topwear(material, color, size) {
this.material = material;
this.color = color;
this.size = size;

Again, this example merely defines the structure of the object; it does not actually create an instance of the object. You'll do that in a minute. Note, in the example, the use of the term “this.” In a sense, think of it as JavaScript shorthand for "this object which you're considering." (There is another situation in which you will use the this keyword; you’ll find out about it in a later chapter. For now, just note its use in defining an object.)

At this stage of the play, you have created the skeleton for any object that will be based on topwear. By skeleton, I mean that you have defined what sort of properties and methods this object would contain. But you haven't yet created an actual instance of an object, such as a sweater object with properties containing actual values. You do that by assigning the above function to a variable, using a special function call known as the new function call. Here’s an example:

sweater = new topwear("cotton" , "black" , "XL");

This example accomplished two feats. First, it created an actual object sweater—just like the one you've been referring to throughout these chapters (except this one doesn't have a price property). Second, it assigned some values to each of sweater's properties. Therefore, after executing the above expression, the following now exists in the mind of your JavaScript program:

Now this object and its properties may be used in the program in any of the circumstances in which you've used objects. So you can create any number of new objects based on the topwear object definition. Simply use the new function call, as shown here:

tanktop = new topwear("nylon" , "white" , "M");
tshirt = new topwear("twill" , "pink" , "XXL");

Now you have tanktop.material, tanktop.color, tanktop.size, and so on and so on for as many new objects as you choose to create. Go wild.

Method Making

Defining an object that contains method properties is basically the same procedure as above. Recall that a method is a property that is, itself, a type of function. So, re-create the topwear definition to include a price calculating function—the one based on material, which you used in an earlier method example and called fprice.

First, you have to create the fprice() method definition (here, you'll use some silly formula to determine the garment price):

function fprice() {
// Base price is $10, add various amounts based on material
var startprice = 10.00;
var addcost = 0;
if (this.material == "cotton") { 
addcost = 5.50;
if (this.material == "nylon") { 
addcost = 2.50;
if (this.material == "argyle") { 
addcost = 20.00;
return startprice + addcost;

Notice, above, the use of this.material. This is a useful form of JavaScript shorthand. Because fprice() is not an independent function but a method of an object, refers to properties in the parent object (topwear). Now that this method definition is created, you will include a call to it in your topwear object definition.

function topwear(material , color , size) { 
this.material = material;
this.color = color;
this.size = size;
this.price = fprice;

Above, when you create the "hook" between the price method of the topwear object and the fprice() function, you simply type the name of the function (with no parentheses or parameters). At this time, you don't want to call the fprice() function, so you merely attach it to the topwear object type.

Finally, create the new object sweater once again.

sweater = new topwear("cotton" , "black" , "XL");

This time, the object sweater contains these properties:


To access the price of a particular sweater, you would call the method sweater.price() with an expression such as

price = sweater.price();

So, quick quiz. Given all of the above, what would the value of price be? 

Answer: price is assigned the value of sweater.price. sweater.price, in turn, refers to the method fprice(), which is part of the object sweater. sweater is an object with properties defined by the definition topwear. sweater.material holds the value "cotton". fprice calculates a total cost based on this material property, which works out to 15.50. Therefore, sweater.price holds the value 15.50, and finally then, price is assigned the value 15.50.

As is good practice when reading programming books, read the previous passage a few more times and follow its logic through the code segments illustrated in the example.

Congratulations are in order. This completes the last of the building blocks of JavaScript programming. Everything you do from now on in JavaScript is based on the concepts covered in Chapters 5 through 8: variables, objects, literals, operators, statements, functions, and methods. The next few chapters will explore how these apply to specific JavaScript and Web-related applications. But first, it’s time for an intermission for rest and recovery (for me, that is; you can continue reading whenever you want).

The Least You Need to Know

This chapter strongly demands a close reading. Nonetheless, contractual obligations being what they are, here’s the obligatory summary:

Previous Chapter Next Chapter

Beginning of ChapterTable of ContentsBook Home PageQue Home Page

For comments or technical support for our books and software, select Talk to Us.
To order books, call us at 800-716-0044 or 317-228-4366.

© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon & Schuster Company.