Chapter 9
Conjunction Junction, What's a Function?
In This Chapter
If statements are the connective tissue of a JavaScript program, functions are the blood. See, that high school anatomy course has really paid off. Any JavaScript program beyond the most basic is going to include functions. Some are prebuilt into JavaScript (as described in the Appendix at the end of this book), while others you will create.
That's great, and very nice to know, but what is a function? A very apropos question, but could you ask it again, and this time a little louder?
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 any sort you want. Therefore, this name 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). To be executed, a function needs to be called from some other section of JavaScript code. You will see how this is done, as well.
| Calling All Functions! |
| When you "call" a function, it means that you instruct JavaScript to execute that function. Remember that a function is a mini-program of JavaScript code. So, "calling" it means to execute the code which comprises a particular function. |
You often use a function to define a procedure that will be called upon regularly. This way, a set routine is programmed and named, and can be called repeatedly without being redefined 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. Eating lunch is a function, and so forth. Between these predefined activities, you act out other tasks, which sometimes are 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, needs to 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. From then on, you could simply call 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.
| 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. |
Functions frequently, although not necessarily, accept parameters when they are called. A parameter is a specified value, which 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?
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; you would notate it the following way:
lunch ("pizza","Coke")
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.
As you will see in later examples, the names you choose when defining the parameters become variables within the function. Consider that you have defined a function lunch(foodstuff, beverage). You may later call this function with specific values, such as lunch("pizza","Coke"). Within the JavaScript code that comprises the function, foodstuff is a variable that would now contain the value "pizza", and beverage is a variable that will now contain the value "Coke".
At the conclusion of a function, it is often (but not always) the case that you will want to return some sort of result to the program that called it. 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 specific 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 (if, say, satisfaction was returned as false, you would 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).
The formal template for a function definition looks like this:
function functionname (parameter1 , parameter2 , etc.)
{ statements }
Therefore, the formal JavaScript definition for the lunch() function would have looked like this:
function lunch (foodstuff , beverage)
{ eat foodstuff ;
drink beverage ;
satisfaction = (evaluation of satisfaction) ;
return satisfaction }
Of course, the statements within brackets in this example are all fake, since there are no real JavaScript statements that define the eating of 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.
An important word about parameters, 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 call
lunch ("pizza" , "Coke")
| 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 leave nothing in between; for example:
function noparams () {statements}
or
noparams ()
|
then 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
lunch (choice1 , choice2)
then within the statements of function lunch(), 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.
You'll see several function calls in action in later examples, but for now, you should get a grasp on the two forms of function calls. Previously, you have just seen one common form-the plain function call. It exists, as written, in the following form:
functionname (parameter1, etc.)
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 does this value get 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, 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, etc.)
Now you're ready to define a real JavaScript function. No more talk about lunch. You will build on an example already coded in the previous chapter. In Chapter 8, you wrote a small segment of JavaScript code that calculated the daily gross profit on product purchases via our Web page. The special exception was that every 10th purchase was free, and thus added zero to your cumulative total.
Now, turn that segment into an official function.
The task: calculate daily gross profit, leaving out every 10th purchase from the total. Return total gross.
First, define the function, which will be called promotion():
function promotion ( orders, price )
Notice that 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, in 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 covered creating objects, 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. This is based closely on the continue statement example from Chapter 8.
{
var total = 0 ;
for (var count = 0; count <= orders; count++)
{ if (( count % 10 ) == 0 )
{ continue };
total += price[count] } ;
return total
}
| Motherly Advice |
| The var situation above is why it is "recommended" to always use a var statement when assigning values to variables. Doing so would prevent any possible mistakes caused by forgetting to use a var statement when necessary. Ultimately, the choice is yours. If you trust yourself to remember to use var statements within functions, then 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. |
For the most part, the above is the same as the code in the continue example. There are a few differences to note:
- The semicolons Remember that each statement within a bracketed section needs to be separated by semicolons. In this case, the variable assignment to total is one statement, the entire for statement is one statement, as is the if clause within the for statement. The final statement-return-does not need a semicolon because it is the final statement before the closing bracket. If you read this paragraph while referring back to the code above, it does make sense.
- The var statement, which is used twice In the previous chapter, we dissed the var statement as being superfluous except for a special case. Welcome to the special case. The "special case" is when you're making new variables within a function. Any variables you create solely for use within the function, such as a loop counter, should be made with a var statement. When done this way, the variable will hold its value only within the function statements. For one thing, this would prevent you from overwriting the value of a variable of the same name which exists in the rest of the JavaScript program.
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 re-animate the two parts and wind up with one fully mature, living, working function.
function promotion ( orders, price )
{
var total = 0 ;
for (var count = 0; count <= orders; count++)
{ if (( count % 10 ) == 0 )
{ continue };
total += price[count] } ;
return total
}
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.
A function call can be made 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
{watchtv ("NBC")}
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.
| Top Loading |
| Because functions must be defined before they can be called, the best way to avoid potential problems is simply to 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 that they will always be loaded before anything else. You'll see an example of this in a later chapter. |
Also note that a function can call another function in the course of its { statements }. However, there is an important rule (looked at 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.
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, the gross profit for the day. Perhaps 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
weektotal = weekly (wkorders , promotion (orders, price))
Supposedly, Marlon Brando was a classic method actor. Now, he was largely before my time (and I stress "largely"), but there are methods in JavaScript programming, as well. Follow 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
sweater.color
However, it is possible for the property, rather than a 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:
sweater.material
sweater.color
sweater.size
sweater.price ()
The first three properties are variables, and thus may be assigned values, or may be assigned to other variables; for example:
sweater.material = "argyle"
or
buystock = sweater.material
However, the fourth property is a method-that is, a function within the object, and, therefore, assigning a value to it is nonsensical. Rather, it is something that you call. For instance, you might call the method sweater.price() and assign the returned result to some other variable:
total += sweater.price ()
That's really all there is to a method. It is simply a function, just like those discussed throughout this chapter; the only difference is that it exists as a property of an object, rather than "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
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. This will provide 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, you'll create separate objects to represent each. Do this by example.
For your first example, simply define a topwear object that does not contain a method. Rather, 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 usage 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, in a later chapter. For now, just note its usage 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. 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:
- sweater.material which is currently the value "cotton"
- sweater.color which is currently the value "black"
- sweater.size which is currently the value "XL"
Now, this object and its properties may be used in the program, in any of the circumstances which you've used objects in.
You can create any number of new objects based on the topwear object definition. Simply use the new function call; for example:
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.
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 the usage of this.material. This is a useful form of JavaScript shorthand. Because fprice() is not an independent function, but a method of an object, this.property 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()
}
Finally, create the new object sweater once again.
sweater = new topwear ("cotton" , "black" , "XL")
This time, the object sweater contains the properties
sweater.material
sweater.color
sweater.size
sweater.price
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 here on in JavaScript is based on chapters 6 through 9, which explained variables, objects, literals, operators, statements, functions, and methods. The next few chapters will explore how these apply to specific JavaScript and Web-related applications. There will now be an intermission for rest and recovery (for me, that is--you can continue reading whenever you like).
This chapter strongly demands a close reading. Nonetheless, contractual obligations being what they are
- A function is a self-contained program code element that is defined one time. It may be called upon by the remainder of the JavaScript program at any time to perform its actions.
- Functions may accept parameters-values given to them upon calling-and may return results to the calling program.
- Functions are defined with the statement
function funcname (parameter1, parameter2, etc.) { statements }
- Functions can be called with a plain call:
funcname (parameter1, etc.)
or in an assignment operator expression if returned results are desired:
variable = funcname (parameter1, etc.)
- Object definitions are created by defining a function that describes the properties of the object (really, it's a good idea to read the chapter to grasp this).
- Methods are functions that are properties of objects. First, their functions are defined, and then they are assigned to a property in the object definition.
- An actual instance of an object is created by making an assignment operator call to an object-defining function using the keyword new. Huh?
objectname = new objfunction (property1, property2, etc.)
- All functions should be defined in the JavaScript program prior to any other code.



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.
© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon & Schuster Company.