Just a moment ago, I explained types by asking you to imagine you had three buckets—one for sand, one for water, and one for pebbles—to build a sand castle. The types were sand, water, and pebbles. The buckets are the variables. In other words, a variable is used to hold values (with the kinds of values limited by the kinds of types). So you can think of a variable as a placeholder for data. As such, variables are an important underlying part of any computer program. If you just have a value—for example, the number 42—you can perform operations on that particular number. But if you have a variable that holds numerical values, you can invent an operation once—and then apply it to a whole mess of values.
For example, a store might want to give a five-percent discount on the price of all items on a particular day. The computer program that generates the total at the checkout register doesn’t have to provide instructions for each item if the item price is stored in a variable. It just applies the discount to the price stored in the variable for the item being purchased. Figure 2-1 shows this simplification.
Figure 2-1: By storing values in variables, each operation doesn’t have to be written in code.
Variable names are identifiers —in other words, they’re made up by the programmer to identify something, in this case a variable. Other kinds of identifiers include labels (used with looping and explained in Chapter 4, “ Working with Loops ”) and function names (discussed in Chapter 5, “ Understanding Functions ”). All identifiers follow the same official rules as identifiers used to denote variables.
There are only a couple of “don’ts” and “gotchas” when dealing with variable names:
Whale salmon pelham123 SSN total_cost L_Name
Don’t get too excited just because you can name a variable pretty much anything you’d like! These are only the official variable-naming requirements.
Following the official rules of the Uniform Building Code is probably necessary for building sound houses that can be resold, but it’s not sufficient for creating well-designed, intuitively functional homes. In the same way, as a matter of good programming practice, you should be careful with variable names. For example, in the list of variable names I just gave you, some identify their likely contents (SSN, total_cost, L_Name) and others don’t (Whale, salmon, pelham123).
A good variable name tells someone reading your code what the variable is supposed to contain. The name should be simple, clear, and—to avoid potential confusion—not too close to any other variable name. (This is also handy for you if you need to change the code at a later date—in case you’ve forgotten, a good variable name will tell you what the variable does!)
You can create variables in your code in two ways:
Using the var keyword. For example, var trekVerb; uses the var keyword to create a variable named trekVerb.
Just by using an identifier as a variable.
|Do It Right!|| |
You should always declare your variables so that it’s clear what they are.
Once you’ve created a variable, you can easily assign a value to it using the assignment operator (which is represented by the equals sign). The assignment operator works in the way you’d think it should—namely, it assigns a value. The later “ Understanding Operators ” section explains operators, including the assignment operator, in greater detail.
It’s high time to work through a few examples of creating variables and assigning them values.
|Try This at Home|| |
To Create a Variable Containing a Value:
Use the var statement to assign a value to a variable. For example:
var trekVerb = "Make ";
Or you can do the following:
If you prefer, you could combine step 1 and step 2: var trekObject = "it so!";.
Now you have two variables, the first containing "Make" and the second containing "it so!" Let’s combine them to create the phrase (from Star Trek: The Next Generation) Make it so! The new, combined phrase will be stored in a new variable. The contents of the new variable will then be displayed in a Web page using the document.write method I showed you in Chapter 1.
Let’s take this from the top, one step at a time.
|Way Cool|| |
You already know how to create the first two variables and assign text to them:
var trekVerb = "Make "; var trekObject; trekObject = "it so!";
Next, create a third variable, trekQuote, and assign the values of the first two variables to it, using the string concatenation operator (+) to connect them:
var trekQuote = trekVerb + trekObject;
var trekVerb = "Make "; var trekObject; trekObject = "it so!"; var trekQuote = trekVerb + trekObject;
the concatenation operator is used to assign the concatenated string "Make it so!" to the variable trekQuote.
The following is another example of string concatenation, which makes a variable named tharn and stores the value "cat" in it. Next, tharn is assigned the value of itself concatenated with the string literal "atonic", and the result is displayed:
var tharn = "cat"; tharn = tharn + "atonic"; document.write(tharn);
As you can see in Figure 2-2, "cat" concatenated with "atonic" makes catatonic.
Figure 2-2: Concatenation appends the string on the right of the string concatenation operator to the end of the string on the left of the operator.
The final step in the Star Trek quotation example is to display the value stored in the variable trekQuote, using the document.write method I explained to you in Chapter 1:
Note a subtle, but important, difference between this line of code and the line of code in Chapter 1. In Chapter 1, we displayed a line of text after the French mathematician and philosopher Descartes:
document.write("I think therefore I am");
In that case, the text displayed was a string literal —in other words, the literal text contained between the quotation marks. In this example, we’re doing something a bit more abstract and powerful: We’re telling the computer to display the contents of the variable trekQuote, whatever that may happen to be.
Listing 2-1 shows making the variables, assigning them values, and concatenating them into the trekQuote variable. As you can see in Figure 2-3, the full phrase is correctly displayed.
Listing 2.1: Concatenating Variables and Displaying the Value Contained
<HTML> <BODY> <H1> <SCRIPT> var trekVerb = "Make "; var trekObject; trekObject = "it so!"; var trekQuote = trekVerb + trekObject; document.write(trekQuote); </SCRIPT> </H1> </BODY> </HTML>
Figure 2-3: The contents of the trekQuote variable is displayed.
I’ve added HTML <H1> </H1> tags to the listing simply to make the display text larger.
You may not need to know about the special fancy characters known as escape sequences (or escape characters), but they sure are useful—and fun! Strictly speaking, it’s not necessary to learn about escape sequences to learn how to program. But most languages use them, and they make some tasks much easier.
Unicode sequence (see http://www.unicode.org for more information about Unicode)
Here’s how this works: Suppose you have a sentence full of single and double quotes that you’d like to display. For example, this if from Harry Potter and the Sorcerer’s Stone:
"I want to read it," said Harry furiously, "as it's mine!"
\"I want to read it,\" said Harry furiously, \"as it\'s mine!\"
Next, the whole thing must be surrounded by single or double quotes before you can assign it to a variable or display it as a string literal:
"\"I want to read it,\" said Harry furiously, \"as it\'s mine!\""
Listing 2-2 shows assigning the escaped string to a variable and then displaying the value stored in the variable. You can see in Figure 2-4 that the quotes are properly displayed.
Listing 2.2: Displaying a String Containing Escaped Quotations
<HTML> <BODY> <H1> <SCRIPT> var potterSays = "\"I want to read it,\" said Harry furiously, \"as it\'s mine!\""; document.write(potterSays); </SCRIPT> </H1> </BODY> </HTML>
|Way Cool|| |
|Try This at Home|| |
If you play with the example I just showed you with escaped quotations, you’ll see that the place where the line of text breaks and forms a new line depends on the size of the browser window and is out of the programmer’s control. (If you look closely at Figure 2-4, you’ll see that with the browser sized as shown, the line break occurs between the words Harry and furiously.)
|Way Cool|| |
First, create a variable named newLine and store the HTML <BR> tag in it:
var newLine = "<BR>";
Next, create variables for each word in the text you want to display:
var One = "One"; var line = "line"; var at = "at"; var a = "a"; var time = "time!";
Note that I’ve named the variables to match their contents, but the variable name isn’t the same thing as its contents.
Next, concatenate the variables with display text and the newLine variable containing the HTML line break tag and then assign the results to a variable named splitLine:
var splitLine = One + newLine + line + newLine + at + newLine + a + newLine + time;
Finally, display the text including HTML:
As you can see in Figure 2-5, the HTML works: The line of text is displayed with breaks where the <BR> character was placed.
Listing 2-3 shows the complete code for concatenating the words and HTML line breaks.
<HTML> <BODY> <H1> <SCRIPT> var newLine = "<BR>"; var One = "One"; var line = "line"; var at = "at"; var a = "a"; var time = "time!"; var splitLine = One + newLine + line + newLine + at + newLine + a + newLine + time; document.write(splitLine); </SCRIPT> </H1> </BODY> </HTML>
The Null type has only one value, null. The null value means that there’s no data in a variable.
The Undefined type also has only one value, undefined. This is the value of a variable whose contents are unclear because nothing has ever been stored in it. (Interestingly, a variable that has never been mentioned in a particular program also has the value of undefined.)
You’ll find out more about Null, Undefined, and NaN as you go on in Learn How to Program.
In contrast, in a strongly typed language you must specify the type of every variable. Unless there’s absolutely no possibility of data being lost, in a strongly typed language automatic type conversion (also called implicit conversion) doesn’t take place.
It’s often the case in programs that you’ll need to convert a type. As a simple example, suppose you’ve performed a calculation and come up with a number. You now want to display the number as part of a string (“Including interest, you owe $42.42. Please pay it at once.”). The process involves converting the number (the result of the calculation) to a string for string concatenation and display.
|Do It Right!|| |
var test = "The answer is " + 42; var test2 = " and "; var test3 = 42 + " is the answer.";
both occurrences of 42 are converted to strings, no matter whether the number is the first value encountered by the variable. If you concatenate the test variables with an HTML line break:
var newLine = "<BR>"; document.write(test + newLine + test2 + newLine + test3 + newLine );
you’ll get the results shown in Figure 2-6.
Bear in mind that most conversion bugs happen during comparisons. If you only compare same types—not mixing numbers and strings—you won’t run into problems.
Conversions to a Boolean type, which contains logical information as explained at the beginning of this chapter, are generally safe if you know the rules. Chapter 3, “ Using Conditional Statements,” explains these conversions.