Chapter 5:
Objects, Names, and Literals
  


In This Chapter

 As you learned in Chapter 3, JavaScript programs reside within the HTML code of a page and enable you to perform a variety of tasks that interact with the user or the user's input. JavaScript is relatively easy to program—even for those who are unfamiliar with computer programming—and it is not generally intended for creating extremely large or complex programs. Readers who have had experience with other programming languages will find JavaScript extremely accessible. New users, however, might want to read the following chapters a few times, to make sure they grasp the concepts involved.

What's in a Name? (A Variable Name, That Is)

One of the basic fundamentals of a programming language is the variable. A variable is essentially a label to which you assign a "value" (what this value might be, you'll learn about shortly). Variables are also commonly used in mathematics. Anyone who recalls having stayed awake during those classes might still be scarred by such statements as "x=5." But that’s good; the trauma will help you when it comes to JavaScript. (And students always want to know of what use algebra will be....)

JavaScript has variables (also known as names or variable names) all over the place, many of them created by you, the programmer. So, first spend some quality time understanding the ubiquitous variable:

Tom, Dick42, and _Harry

Generally, it is up to you, the programmer, to decide on variable names. But as you might guess, JavaScript has a few rules that govern what names are allowable:

As long as you abide by the preceding rules, JavaScript doesn't care what you choose to name a variable. As far as JavaScript is concerned, the same variable name will always refer to the same value placeholder, whether that name is x or inventory. However, you should care. As the programmer, you want to maximize your ability to understand and follow your own program. This is especially true when you inevitably must debug it (that is, find where problems are and attempt to fix them). So it is in your best interest to make up variable names that hold some human meaning in relation to the values they will represent.

For example, let's suppose that you have a Web page you’re using to sell a product: You're hawking novelty mugs with pictures of your dog wearing a bikini. The prices of these may vary, depending on how many mugs the consumer chooses to purchase at one time. The first variable you'll need to name is the one that refers to the number of mugs ordered. Remember, you can name this variable anything (within the rules above), such as x or bazoo. But, for the sake of programming clarity to the human mind, mugs is probably a good choice for a variable name. (Of course, orders would suffice, too, but you get the concept.)

There is a second variable in the preceding example, and that is the price of each mug. Let’s say the single-mug purchase price is $9.95, but two mugs sell for $15.95, and three sell for $22.95. Because the price may vary and cannot be assumed to be constant, it will require a variable name, as well. Again, you could name the price variable mary or y, but something like price or cost seems to be a more reasonable choice.

Full of Value(s)

As you've read, variables are references to values. Now that you understand what a variable is, look at the values a variable might hold. In JavaScript, a variable might refer to any of three types of values, plus a special bonus value (I know this doesn't make sense yet, but bear with me.)

And the special bonus value is this:

Handing Out Assignments

When you create a variable name and refer it to a value, you are making an assignment. For example, in our earlier example, we "assigned the numeric value 5 to the variable mugs." Although you'll discover more complex assignments in Chapter 7, the basics below serve as a useful grounding (you'll learn exactly how and where to place these commands as part of a JavaScript program in Chapter 7).

Your Basic Assignment

A basic assignment in JavaScript is made with this construction:

var variablename = value;
where var is the keyword that precedes all assignments, variablename stands for the name of the variable, and value stands for the value you are assigning to the variable. For example:
var mugs = 2;
var price = 9.95;

Assigning a String to a Variable

When making an assignment to a string value, it is vital to place the string within quotation marks (either the double or single kind). Here are two examples:

var surname = "Carruthers";
var model = 'C3PO';
Note that if you do not include the quotation marks, JavaScript will think you are assigning the value of one variable to another variable; for example:
var surname = carruthers;
JavaScript will think you want to assign the value of the variable carruthers to the variable surname. Because carruthers is a nonexistent variable, JavaScript will display an error message to alert you. This is not what you want in this case (although at other times, you might want to assign one variable's value to another).

Boolean Assignments

Boolean values usually represent conditions such as matters in which there can be only a true or false status. A Boolean value assigned to a variable simply looks like this:

var married = true;
var dead = false;

...And Don't Forget Null

And, for the sake of closure, an assignment of the special bonus value, null:

var variablename = null;
You may or may not encounter actual applications of the null value assignment in later chapters. It's not crucial, and it may not come up very often. A common technique among programmers who want a variable to contain "nothing" is to assign numeric variables the value 0 (for example, total = 0) and to assign string variables the value "" (for example, surname = ""). This is because, in many instances, we want numerical variables to begin with a value of zero (as in variables which keep count of something, for example), and we often want string variables to begin as a string with no characters.

The Plain (Literal) Truth

A value that is not married (assigned) to a variable is known as a literal. This is such a simple concept that it might actually be a tad confusing at first. To wit:

What is the point of any of this? Recall that variables are most often used to track potentially changing values. In some instances, you will want to refer to a value, but it may be one constant amount. For example, perhaps the price of your product is 9.95, and it is always 9.95 in all cases.

In these instances, you still have the option to assign a variable name to a constant value, which often makes reading the JavaScript program easier for human debugging purposes. However, you do not need to use a variable at all in these cases. You may simply want to write out 9.95 whenever it is needed in a calculation within the JavaScript program. This is a reasonable practice in some cases, but in others it would be more comprehensible to use a meaningful variable name.

 
Stay Still
 
A constant is a label whose value never changes. A typical example from "the real world" is PI. We use the label PI or that funny symbol , yet it always represents the same actual number. We may choose to use a similar technique in JavaScript programming for ease of reading and ease of future program modifications.
The following examples use a variable assignment and the * sign, which is a multiplication symbol (we'll learn more about that in the next chapter). To illustrate a literal versus a variable name, consider the following:
Using variables:
var price = 9.95;
var total = mugs * price;
Using literals:
var total = mugs * 9.95;
Although both sets of commands yield the same results, there are different reasons to select one approach or the other. In the first case (using variables), the calculation for the variable total is very easy for a human reading the program code to understand (for debugging purposes). In the second case, it might not be so obvious to a human reader just what the 9.95 represents. If there is a problem with the program, analyzing it may be more difficult because of this. 

Secondly, imagine that there might be many instances of calculations within the program that utilize the 9.95 price. If the price were to change, it would take some time to manually edit the JavaScript program to reflect the price change. On the other hand, in the first example, you would only need to change the value assigned to price one time, and because price is used to represent the value throughout the remainder of the program, all other calculations would remain accurate without your having to find them and change them.

Treating Values Like Objects

So far, you've learned about two important topics (variable names and their assigned values) and one minor topic(literals). Now, it is time to move up one rung on the ladder of abstraction to a very relevant concept in JavaScript programming: the object.

In JavaScript, an object is an umbrella concept under which a set of variables resides. This may be a tough concept at first, so let me explain it several different ways. Consider a sweater. A sweater, by the JavaScript definition, is an "object" that possesses several noteworthy qualities or properties. For example, a sweater may possess properties of material, size, color, and price.

Note that each property sounds like the variables discussed earlier. That is exactly what they are. Thus, an object is a sort of "supervariable" that contains a set of subvariables. Another example of an object would be an individual person. A person, as an object, contains a set of properties, some of which are useful for our particular application—such as first name, surname, age, gender, and marital status.

Also take note of how objects can fit inside other larger objects. For example, a person object could be part of a family object. A family object might have properties such as size, ethnicity, combined income, and persons (each of which, in turn, possesses its own individual person object properties previously described). Therefore, an object can also be a property of another object. Confusing? Somewhat, but useful as well, as you shall see.

In JavaScript lingo, you denote an object and its properties in the form object.property. For example, recall the sweater object. Imagine that in JavaScript, you create an object called sweater (for now, don't worry about how you create an object). You then create several properties for the sweater object: material, size, color, and price. In JavaScript syntax, you would refer to those properties in program code like this:

sweater.material
sweater.size
sweater.color
sweater.price
Each of the preceding is a variable of the same sort discussed at the opening of this chapter. Therefore, you can assign appropriate values to each of them. Examples include the following:
sweater.material = "argyle";
sweater.size = "M";
sweater.color = "violet";
sweater.price = 29.95;
Objects are common in JavaScript programs, so this is an important concept to nail down. Object properties exist in the order in which they were originally defined. You won't learn how to define objects until Chapter 8, but you should remember this point. 

A la Carte versus Prepackaged Objects

Keep in mind that you don't have to create objects. They're necessary only if they are useful to the tasks of your JavaScript program. A simple program that merely performs calculations using two variables may not need any objects. However, in addition to objects that you may choose to create, JavaScript also includes a number of premade objects. These exist to help you achieve certain ends in your program. But before you take a closer look at some built-in objects, you need to learn about functions, and all of that fun takes place in Chapter 8.

So far, you've looked at variables, the values that may be assigned to them, literals, and objects, which are superset groups of variables (known as properties). Here, break for tea and crackers, which are provided in the rec room down the hall. See you in a bit.

The Least You Need to Know

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.