Understanding Variables


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.

click to expand
Figure 2-1: By storing values in variables, each operation doesn’t have to be written in code.

Naming Variables

It’s easy to name a JavaScript variable because variables can be named pretty much anything you’d like provided the name begins with a letter. Variable names can also begin with an underscore (_) or a dollar sign ($).

Any characters after the first character can be a letter, digit, underscore, or dollar sign. (Digits aren’t allowed as the first character so that JavaScript can easily distinguish identifiers from numerical values in your code.)

Note

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:

A variable name can’t be the same as any JavaScript keyword. For example, you can’t name a variable if.

In JavaScript, variable names are case sensitive. This means that myVariable identifies a different variable than Myvariable, both of which are different animals than myvariable. Watch out for this one; this kind of thing can introduce errors into programs and be tricky to spot!

Here are some examples of legal JavaScript 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!)

Creating Variables

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.

Creating a variable just by using it—in other words, without declaring it using var —works okay but is not good practice. If the JavaScript interpreter sees the identifier trekVerb without a declaration, and it makes sense to use the identifier as a variable, that’s what will happen. But it’s bad programming practice because it’s not necessarily clear at a casual glance what the identifier is.

Do It Right!

You should always declare your variables so that it’s clear what they are.

Assigning Values to Variables

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:

  1. Create a variable using the var statement. For example:

     var trekObject; 

  2. Assign a value to the variable. For example:

     trekObject = "it so!"; 

Note

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; 

start sidebar
Using the String Concatenation Operator

In everyday usage, the plus sign (+) is used to add two numbers together. For example, 1 + 1 = 2. The plus sign is used this way in JavaScript, as well—and is called the addition or additive operator.

However, when strings are involved rather than numbers, the plus sign tells JavaScript to concatenate the string values. This means to append the string on the right of the operator to the string to the left of the operator. In the following example:

 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.

click to expand
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.

end sidebar

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:

 document.write(trekQuote); 

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

start example
 <HTML> <BODY> <H1> <SCRIPT>     var trekVerb = "Make ";     var trekObject;     trekObject = "it so!";     var trekQuote = trekVerb + trekObject;     document.write(trekQuote);  </SCRIPT> </H1> </BODY> </HTML> 
end example

click to expand
Figure 2-3: The contents of the trekQuote variable is displayed.

Note

I’ve added HTML <H1> </H1> tags to the listing simply to make the display text larger.

Using Some Fancy Characters

Advanced

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.

All the JavaScript escape sequences begin with a backslash (\). Table 2-2 shows some of the JavaScript escape sequences you can use.

Table 2-2: JavaScript Escape Sequences

Escape Sequence

Meaning

\b

Backspace

\t

Tab

\n

New line

\f

Form feed

\h

Hexadecimal sequence

\r

Carriage return

\u

Unicode sequence (see http://www.unicode.org for more information about Unicode)

\"

Double quote

\'

Single quote

\\

Backslash (\)

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!" 

To change the double quotes and single quote (that is, the apostrophe) in this sentence so that they can be displayed as a JavaScript string, they must be escaped. Here’s how this looks:

 \"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

start example
 <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> 
end example

Way Cool

click to expand
Figure 2-4: It’s easy to display quotations using escape sequences.

Let’s Have HTML for Dinner!

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.)

You may have wondered if you can embed HTML within JavaScript strings. The answer is that you can—HTML is just plain text like any other text string. Let’s use the HTML line break tag— <BR> —to create line breaks where we’d like them in a JavaScript string displayed with the document.write method. This will also give us a chance to practice assigning and concatenating variables.

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:

 document.write(splitLine); 

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.

click to expand
Figure 2-5: You can include HTML tags in JavaScript strings.

Listing 2-3 shows the complete code for concatenating the words and HTML line breaks.

Listing 2.3: Embedding HTML in a JavaScript String

start example
 <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> 
end example

start sidebar
Advanced—Examining Some Special Types

In addition to the three standard types—Boolean, Number, and String—that I’ve told you about earlier in this chapter, there are two other special types in JavaScript: Null and Undefined.

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 should also know about NaN. NaN is an important property of the JavaScript Number object. It’s short for Not a Number and is the result of a mathematical operation such as dividing a number by zero that has no numerical answer. NaN is unequal to any number and doesn’t even equal itself.

You’ll find out more about Null, Undefined, and NaN as you go on in Learn How to Program.

end sidebar

Implementing Type Conversion

JavaScript is a loosely typed language. This means you don’t specify the type of a variable when you create it. Variables are automatically converted to reflect the type of values stored in them during program execution depending on the JavaScript interpreter’s analysis of the context in which a variable is being used. This makes things seem easy because you don’t have to manually specify type conversions, but it also means that there’s a greater possibility of error because of unexpected consequences of automatic type conversion.

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!

As a matter of good coding practice, you should attempt to perform conversions yourself rather than letting JavaScript do it for you automatically. A number of JavaScript functions are available for performing type conversions, including those shown in Table 2-3. (When you perform a type conversion using one of these functions rather than allowing JavaScript to automatically perform a conversion for you, it is called an explicit type conversion.)

Advanced
Table 2-3: JavaScript Type Conversion Functions

Function

Name What It Does

eval

Evaluates an expression and returns its value. If the expression consists of JavaScript statements, these are executed and a value provided by the last executed statement is returned.

parseInt

Converts a string to an integer (NaN returned if this isn’t possible).

parseFloat

Converts a string to a floating-point number (NaN is returned if this isn’t possible).

As a general rule of thumb, JavaScript automatically converts numbers to strings rather than the other way around. Thus, in these statements:

 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.

click to expand
Figure 2-6: JavaScript implicitly converts numbers to strings rather than the other way around.

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.




Learn How to Program Using Any Web Browser
Learn How to Program Using Any Web Browser
ISBN: 1590591135
EAN: 2147483647
Year: 2006
Pages: 115
Authors: Harold Davis

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net