Que Logo

Chapter 6

Objects, Names, and Literals


In This Chapter


Debate: Script or Program?
What is the difference between a programming language and a scripting language? Technically, JavaScript is scripting, not programming. Thus, its code is a script rather than a program. Generally, programming languages are more complex, require more specific instructions and definitions from the programmer, and are suitable for creating large, efficient applications. Scripting languages are "looser"-they require less discipline and complexity on the author's part, and are more suited to small tasks here and there. JavaScript borrows some from programming languages such as Pascal and C, and some from scripting languages such as Perl and REXX. Among the variety of programming and scripting languages around, JavaScript is one of the easier and less complex of them.
Welcome to JavaScript. What is a JavaScript? Quasi-technically speaking, it is a programming language that enables you to expand the functionality of your Web pages. JavaScript programs reside within the HTML code of a page and allow 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 unfamiliar with computer programming, and is not generally intended for creating extremely large or complex programs. Any readers who have had experience with any other programming languages will find JavaScript extremely accessible. New users might want to read the following chapters a few times, to 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 may be, you'll learn about shortly). Variables are also commonly used in mathematics, so anyone who recalls having stayed awake during those classes may still be scarred by such statements as "x=5." Good, this trauma will help you when it comes to JavaScript (and students always want to know of what use algebra will be!).
JavaScript will have variables all over the place, many of them created by you, the programmer. So, first spend some quality time understanding the ubiquitous variable.
Because it is a label, the variable is used to refer to a given "value" in a program. The value that the label refers to may change, although the label will stay the same. For example, at one point in our program, the variable "x" might refer to the value "5," but at a later point in the program, "x" might refer to 10. This is not arbitrary--perhaps we have used "x" to track the number of items a user has chosen to purchase, and one user ordered 5 while another bought 10. The variable (also known as a name or variable name) allows us to instruct the computer to perform a series of tasks or calculations, whatever the actual values may be. This, in a sense, is the heart-or one of the hearts (if that's possible)--of a program, and a JavaScript program in particular.

Tom, Dick42, and _Harry


Generally, it is up to you, the programmer, to decide on variable names. JavaScript does have a few rules that govern what names are allowable:
Other than 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 that they will represent.
For example, let's suppose that you have a Web page used 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. Perhaps orders would suffice, too, but you see the concept.
There is a second variable in the preceding example, and that is the price of each mug. The single-mug purchase price might be $9.95, but perhaps two mugs sell for $15.95, and three for $22.95. Because the price may vary, and cannot be assumed to be constant, it will require a variable name, as well. So, again, we could name the price variable mary, or y, but something like price or cost seems to be the more reasonable choice.

Full of Value(s)


As you've read, variables are references to values. So, now that you understand what a variable is, look at the values a variable may hold. In JavaScript, a variable may refer to three types of values, plus a special bonus value. This doesn't make sense yet, but bear with me.
…And the special bonus value:

Handing Out Assignments


When you create a variable name and refer it to a value, that is an assignment, as in, "We assigned the numeric value 5 to the variable mugs." Although you'll discover more complex assignments in Chapter 8, 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 8).

Your Basic Assignment


A basic assignment in JavaScript is made with the 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 = "Caruthers"
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 = caruthers 

JavaScript will think you want to assign the value of the variable caruthers to surname. Since caruthers is a nonexistent variable, JavaScript will display an error message alerting you to this fact. This is not what you want in this case (though at other times you do 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. Assigning a Boolean value 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 application for the null value assignment in later chapters. It's not crucial, and may not come up very often. A common programming technique when wanting a variable to contain "nothing" is to assign numerical variables the value 0 (for example, total=0) and to string variables, the value "" (for example, surname=""). Either of these practices would work just as well as the null assignment.

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:
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.
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 only 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 it-this often makes reading the JavaScript program easier for human debugging purposes--but you do not need to use a variable 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, and other times it would be more comprehensible to use a meaningful variable name.
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 pro-gram which 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 changes. On the other hand, in the first example, one need only 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 will remain accurate as-is.
Lastly, to reiterate, all of the above assumes that the price in question will remain constant. If it may change for any reason, such as to calculate discounts, it must be represented by a variable name.

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 in the ladder of abstraction, to a very relevant concept in JavaScript programming: the object.
An object, in JavaScript, is an umbrella concept under which a set of variables resides. This may be a tough concept at first, so let's 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 how 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 notice 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 each person (who, in turn, possess their 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

The New Math?
You may have noticed that you often start counting from 0 in programming. Why? The computer likes it that way. Therefore, in many computer counting scenarios, 0 represents "the first place," 1 is "the second place," and so on. It is somewhat confusing, which is why those who program frequently have the sort of hair that they do. In any case, it's just a matter of remembering that as you program.
For example, recall the sweater object. Imagine that in JavaScript, you create an object (for now, don't worry about how you create an object) called sweater. You then create several properties for the sweater object: material, size, color, and price. In JavaScript syntax, these would be referred to in program code as

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 would include

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 9, but simply remember this point. In the spirit of that order, you can refer to the properties in an alternate way:
sweater[0] is equivalent to sweater.material
sweater[1] is equivalent to sweater.size
and so on.
For humans, sweater.material is certainly the preferable way to write code; however, there are times you may want to use the index numbers (the digits within the brackets) on occasions that you'll encounter later.

Objects à la Carte vs. Prepackaged


For the Programmers Out There…
If you've done any programming in the past, you may notice the similarity between objects in JavaScript and "arrays" in most other languages. That's no coincidence-they are the same thing. You can even refer to object properties in JavaScript in a more traditional array-like fashion, such as
sweater["size"] = "M"
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, besides any 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.
Before you take a closer look at some built-in objects, you need to learn about functions, all the fun of which 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.
© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon & Schuster Company.