Chapter 3
Using Variables
Key Skills & Concepts
    Understanding Variables
    Why Variables Are Useful
    Defining Variables for Your Scripts
    Understanding Variable Types
    Using Variables in Scripts
image
Now that you have learned the basics of adding JavaScript to a Web page, it is time to get into the inner workings of the language. Since variables are an important part of JavaScript coding, you will need to know as much as possible about what they are and why they are useful in your scripts. Once you have an understanding of how variables work and what they can do, you will be able to move on to other topics that build on the use of the various types of variables.
In this chapter, you will begin by learning what variables are and why they are useful. You will then move on to find out about the methods that are used to declare variables and how to assign a value to a variable. Finally, you will see how to use variables in your scripts.
Understanding Variables
A variable represents or holds a value. The actual value of a variable can be changed at any time. To understand what a variable is, consider a basic statement that you may recall from algebra class:
x=2
The letter x is used as the name of the variable. It is assigned a value of 2. To change the value, you simply give x a new assignment:
x=4
The name of the variable stays the same, but now it represents a different value.
Taking the math class example one step further, you probably had to solve a problem like this one:
If x=2, then 3+x=?
To get the answer, you put the value of 2 in place of the variable x in the problem, for 3+2=5. If the value of x changes, so does the answer to the problem. So, if x=7, then the calculation turns into 3+7, and now the result is 10.
Variables in JavaScript are much like those used in mathematics. You give a variable a name, and then assign it values based on your needs. If the value of the variable changes, it will change something that happens within the script.
Why Variables Are Useful
Using variables offers several benefits:
    They can be used in places where the value they represent is unknown when the code is written.
    They can save you time in writing and updating your scripts.
    They can make the purpose of your code clearer.
Variables as Placeholders for Unknown Values
Often, a variable will hold a place in memory for a value that is unknown at the time the script is written. A variable value might change based on something entered by the viewer, or it may be changed by you later in the script code.
For instance, you might have a function that takes in certain values based on user input (functions will be discussed in Chapter 4). Since the value of user input is unknown at the time the script is written, a variable can be used to hold the value that will be input by the user. This is true for any sort of user input, whether it be in the form of a JavaScript prompt/confirm box, input fields in a form, or other methods of input.
Variables as Time-Savers
Variables speed up script writing because their values can change. When you assign a value to a variable at the beginning of a script, the rest of the script can simply use the variable in its place. If you decide to change the value later, you need to change the code in only one place—where you assigned a value to the variable—rather than in numerous places.
For instance, suppose that back in math class, you were asked to solve this problem:
If x=2, then 3+x-1+2-x=?
You know that you need to substitute the value of 2 for each x that appears, for 3+2–1+2–2=4. Now if the teacher wants you to do this problem again with a different value for x, the whole problem does not need to be rewritten. The teacher can just give you the following instruction:
Solve the above problem for x=4.
The longer and more complex the problem gets, the more useful the variable becomes. Rather than rewriting the same thing over and over, you can change one variable to offer an entirely new result.
Variables as Code Clarifiers
Since variables represent something, and you can give them meaningful names, they are often easier to recognize when you read over (and debug) your scripts. If you just add numbers, you may forget what they stand for. For example, consider this line of code:
image
Here, the numbers could mean almost anything. Instead, you might assign 2.42 as the value of a variable named CandyPrice and 4.33 as the value of a variable named OilPrice:
image
Now, rather than trying to remember the meaning of the numbers, you can see that the script is adding the price of some candy to the price of some oil. This is also useful in debugging, because the meaningful variable names make it easier to spot errors.
Defining Variables for Your Scripts
Now that you understand what variables are and why you want to use them, you need to learn how to make them work in your scripts. You create variables by declaring them. Then you assign values to them using the JavaScript assignment operator. When you name your variables, you need to follow the rules for naming variables in JavaScript, as well as consider the meaningfulness of the name.
Declaring Variables
To declare text as a variable, you use the var keyword, which tells the browser that the text to follow will be the name of a new variable:
image
For example, to name your variable coolcar, the declaration looks like this:
image
In this example, you have a new variable with the name coolcar. The semicolon ends the statement. The variable coolcar does not have a value assigned to it yet (JavaScript will give it a value of undefined).
To declare multiple variables, one option is to use the var statement each time:
image
Alternatively, you can use a single var statement and separate each variable name with commas, making sure the last one ends in a semicolon (to end the var statement):
image
As described in the next section, you can give your variables a value at the same time that you declare them, or you can assign them a value later in your script.
Assigning Values to Variables
The code for giving a variable a name is simple, but there are some restrictions on words that you can use for variables and the cases of the letters. To assign a value to a variable, you use the JavaScript assignment operator, which is the equal to (=) symbol. If you want to declare a variable and assign a value to it on the same line, use this format:
image
For example, to name your variable paycheck and give it the numeric value 1200, use this statement:
image
The statement begins with the keyword var, followed by the variable paycheck, just as in the plain variable declaration described in the previous section. Next comes the assignment operator (=), which tells the browser to assign the value on the right side of the operator to the variable on the left side of the operator. To the right of the assignment operator is 1200, which is the numeric value being assigned to the variable paycheck. The line ends with a semicolon to mark the end of the statement.
CAUTION
image
Be careful not to think of the assignment operator (=) as having the meaning “is equal to.” This operator only assigns a value. The operator for “is equal to” is two equal signs together (==), as you’ll learn in Chapter 5.
To declare and assign another variable, you use the same format. For example, to set up a variable named spending to track the amount of money you are spending from the paycheck variable, use these statements:
image
Of course, you will also notice that this financial situation is headed for trouble, since the money being spent in the spending variable is more than what is being brought in with the paycheck variable. Oddly, it is starting to look like the budget for my Web site!
The method you used earlier to declare multiple variables with a single var statement will also work to declare and assign values to multiple variables. Commas are used to separate each variable assignment, as shown in the following code:
image
Again, remember that the last variable that is declared and assigned a value will end with a semicolon to complete the var statement.
The examples you’ve seen illustrate the proper and safe way to code variable declarations and assignments. However, JavaScript allows a certain amount of flexibility when it comes to variables. In many cases, the code will work without using precise coding syntax. For example, you may see some scripts written without using the var keyword the first time a variable is used. JavaScript will often declare the variable the first time it is used even if it is previously undeclared. An example is shown here:
image
This works since the variable is being assigned a value (JavaScript will simply declare the variable and assign it the value of 1200). However, if you were trying to declare the variable without an assignment, the following would not be valid:
image
This declaration would still require the var keyword to be valid, as in the following code:
image
You may also see a script that leaves off the ending semicolon:
image
And in some scripts, both features are left out of the variable assignment:
image
All of these shortcuts may seem handy, but it is best to go ahead and define each variable before using it, use the var keyword, and include the semicolon. Not doing so can cause errors in some browsers and may give people the impression the code was not written well. Also, any of these omissions can be really troublesome if you need to debug the script. Giving variables the correct declarations and assignments will avoid problems, and your code will be easier to read and understand.
Naming Variables
Before you start naming your own variables, you need to be aware of JavaScript’s naming rules. The factors you need to consider when choosing names are case sensitivity, invalid characters, and the names that are reserved by JavaScript. Additionally, you should try to give your variables names that are both easy to remember and meaningful.
Using Case in Variables
JavaScript variables are case sensitive—paycheck, PAYCHECK, Paycheck, and PaYcHeCk are four different variables. When you create a variable, you need to be sure to use the same case when you write that variable’s name later in the script. If you change the capitalization at all, JavaScript sees it as a new variable or returns an error. Either way, it can cause problems with your script.
Here are a couple of suggestions for using case in your variable names:
    If you are using a variable name that consists of only one word, it is probably easiest to use lowercase for the entire name. It will be quicker to type, and you will know when you use it later to type it all in lowercase.
    For a variable name with two words, you might decide to capitalize the first letter of each word. For example, you may name a variable MyCar or My_Car (you will see more on the underscore character, _, in the next section). You also might use what is called “camelCase,” where you leave the first word in lowercase and make each subsequent word uppercase. For example, you may name a variable myCar or myCoolCar.
The capitalization of variables is entirely up to you, so you should use whatever style you are most comfortable with. It is best that you adopt a convention and continue to use it. For instance, if you name a variable using lowercase characters only, you should do the same throughout the script to avoid accidentally switching the case when using the variable later. In this book, I use only lowercase characters for variable names, to keep the code clear.
Using Allowed Characters
An important rule to remember is that a variable name must begin with a letter, underscore ( _ ), or dollar character ($). The variable name cannot begin with a number or any other character that is not a letter (other than the underscore and dollar). The other characters in the variable name can be letters, numbers, underscores, and dollar characters. Blank spaces are not allowed in variable names. So, the following variable names would be valid:
    paycheck
    _paycheck
    pay2check
    pay_check
    $pay_245
However, the following variable names are not valid:
    #paycheck
    1paycheck
    pay check
    pay_check 2
    _pay check
The hardest rule to remember may be that you cannot begin the name with a number (it’s the one I forget most often). While such a name may look valid, JavaScript doesn’t allow it.
Avoiding Keywords and Reserved Words
Another rule to keep in mind when naming your variables is to avoid the use of JavaScript keywords and reserved words. Keywords are special words that are used for a specific purpose in JavaScript. For instance, you’ve learned that the reserved word var is used to declare a JavaScript variable. Using it as a variable name can cause numerous problems in your script, since this word is meant to be used in a different way. Reserved words are special words that are reserved to be used as keywords at a later date, so they should also not be used as variable names, in order to prevent your code from having potential problems in the future.
Table 3-1 lists the keywords and reserved words in JavaScript. Note that all of these words are in all lowercase letters. In later chapters, you will use a number of the keywords, so they will become more familiar over time.
image
image
Table 3-1    JavaScript Keywords and Reserved Words
Giving Variables Meaningful Names
Although x is an acceptable variable name, it is unlikely that you will be able to remember what it stands for if you need to debug the program later. Also, if someone else is trying to help you debug the code, their job will be even harder.
You should try to give your variables names that describe what they represent as clearly as possible. Suppose that you want to use a variable to hold a number of an example on a page. Rather than use x, ex, or another short variable, use something more descriptive:
image
The variable examplenumber will be easy for you to recognize later, and other coders will be more likely to understand its use quickly.
The more variables you use in a script, the more important it becomes to use meaningful and memorable names.
Understanding Data Types
So far, you’ve seen examples of variable values that are numbers. In JavaScript, the variable values can be one of several data types, which include number, string, Boolean, null, and undefined.
Unlike stricter programming languages, JavaScript does not force you to declare the type of variable when you define it. Instead, JavaScript allows virtually any value to be assigned to any variable. It also allows you to change the data type if you change the value. Although this gives you flexibility in coding, you need to be careful because you can end up with some unexpected results—especially when adding numbers (see Chapter 5 for more on this topic).
Number
Number variables are just that—numbers. JavaScript does not require numbers to be declared as integers, floating-point (decimal) numbers, or any other number type. Instead, any number is seen as just another number, whether it is 7, –2, 3.453, or anything else. The number will remain the same type unless you perform a calculation to change the type. For instance, if you use an integer in a variable, it won’t suddenly have decimal places unless you perform a calculation of some sort to change it (dividing unevenly, for instance).
As you’ve seen, you define a number variable by using the keyword var:
image
Here are some examples:
image
If you need to use a particularly long number, JavaScript has exponential notation. To denote the exponent, use a letter e right after the base number and before the exponent. For example, to create a variable named bignumber and assign it a value of 4.52 × 105 (452,000), put the letter e in place of everything between the number and the exponent (to represent the phrase “times 10 to the power of”):
image
NOTE
image
JavaScript may return an answer to a calculation using exponential notation (like many calculators).
String
String variables are variables that represent a string of text. The string may contain letters, words, spaces, numbers, symbols, or most anything you like. Strings are defined in a slightly different way than numbers, using this format:
image
Here are some examples of string variables:
image
As you can see, strings can be short, long, or anything in between. You can place all sorts of text and other characters inside string variables. However, the quotation marks, some special characters, and the case sensitivity of strings need to be considered.
Matching the Quotation Marks
In JavaScript, you define strings by placing them inside quotation marks (quotes, for short), as you saw in the examples. JavaScript allows you to use either double quotes or single quotes to define a string value. The catch is that if the string is opened with double quotes, it must be closed with double quotes:
image
The same goes for single quotes:
image
Trying to close the string with a nonmatching type of quotation mark, or leaving out an opening or closing quotation mark, will cause problems.
image
These mistakes will result in an “Unterminated String” error in the Web browser.
NOTE
image
If you use double quotes to enclose the string, you can use single quotes inside the string and vice versa.
Watching the Case
JavaScript strings are case sensitive. This may not seem important now, but it matters when you need to compare strings for a match. It only takes one character in a different case to make the strings different:
image
You’ll learn more about string comparisons in Chapter 5.
Using Special Characters
Special characters enable you to add things to your strings that could not be added otherwise. For example, suppose that you need a tab character between each word in a string. If you press the tab key on the keyboard, JavaScript will probably see it as a bunch of spaces. Instead, use the special character , which places a tab in the string, as in this example:
image
In each spot where the special character appears, JavaScript interprets a tab character.
The special characters all begin with a backslash character (). Thus, if you want a single backslash character in your string, you need to use the special code for a backslash: \. For instance, suppose you wish to write the following sentence on a Web page: “Go to the directory c:javascript on your computer.” If you use the string as it is written, your code would look like this:
image
The problem is that the single backslash would not be printed on the Web page. It would appear as
image
Unless the backslash is followed with the code for a special character, JavaScript prints the character after the slash as it appears (you will see this in the escape technique discussed in the next section). To fix this, use the \ special code to print a single backslash on the page:
image
Now you get the sentence you want printed to the browser, like this:
image
The special characters used in JavaScript are shown in Table 3-2.
image
image
Table 3-2   Special JavaScript Characters
Suppose that you want to print a sentence on a Web page with strong emphasis. JavaScript allows you to print HTML code to the page as part of a string in the document.write() method (which you used for your first scripts in Chapter 2). To do this, you can add in the <strong> and </strong> tags from HTML, as in this sample code:
image
Now suppose that you want the code itself to appear on two lines when it is viewed (via “View Source” in the browser), like this:
image
You can do this by adding the newline special character to the code:
image
The special code is only a newline in JavaScript; it will not result in an HTML line break. The JavaScript newline code does not add a new line to the result of the code shown in the browser display. So, the end result of the preceding code is a sentence like this one:
image
If you want to add a line break in the browser display, you need to use the HTML <br /> tag to produce it.
Keep in mind that the JavaScript newline affects only the appearance of the source code; it is not a factor in the end result. However, it does help later when you want to format the output of JavaScript alert boxes and various other JavaScript constructions.
Escaping Characters
JavaScript allows you to escape certain characters, so that they will show up correctly and avoid causing errors. Like special characters, escape sequences use the backslash character (), which precedes the character that needs to be escaped.
As noted earlier, JavaScript checks each string for the presence of special characters before rendering it. This is useful if you want to have a quote within a string. For example, suppose that you want to print the following sentence on a Web page:
image
What would happen if you just threw it all into a document.write() command?
image
If you look near the end of the document.write() line, you will see that the two double quotes together could cause trouble, but the browser will actually get upset before that point. When the double quote is used before the word JavaScript, the browser thinks you have closed the string used in the document.write() command and expects the ending parenthesis and semicolon. Instead, there is more text, and the browser gets confused.
To avoid problems with quotes, use the backslash character to escape the quotation marks inside the string. By placing a backslash in front of each of the interior double quote marks, you force them to be seen as part of the text string, rather than as part of the JavaScript statement:
image
This fixes the problem with the string, and the sentence will print with the quotation marks.
CAUTION
image
Also watch for single quotes and apostrophes within strings. Escaping these is required for strings enclosed within single quotes.
The escape technique also works for HTML code in which you need quotation marks. For instance, if you want to put a link on a page, you use the anchor tag and place the URL in quotes. If you escape the quotes in the anchor tag, JavaScript allows you to write the HTML code to the page within the document.write() method, as in this example:
image
This does the job, but there is also an easier way to make this work if you do not want to escape quotation marks all of the time.
To avoid escaping the quotes in the preceding code, you could use single quotes around the URL address instead, as in this code:
image
You can also do this the other way around if you prefer to use single quotes on the outside, as in this example:
image
The important point to remember here is to be sure that you do not use the same type of quotation marks inside the string as you use to enclose the string. If you need to go more than one level deep with the quotes, you need to start escaping the quotes; this is because if you switch again, it will terminate the string. For example, look at this code:
image
The first one would work, since the quotes are escaped to keep the string going. However, the second line only switches back to double quotes when inside the single quotes within the string. Placing the double quotes there without escaping them causes the string to terminate and gives an error.
As you can see, quotation marks can be a real pain when you need to use a large number of them within a string. However, remembering to use the backslash to escape the quotes when necessary will save you quite a few headaches when you are looking for a missing quote. I’ve had to look for missing quotes in my code a number of times, and my head was spinning after a few of those encounters! Later in this chapter, you will see that you can add strings together, which can simplify the use of quotes for you.
Boolean
A Boolean variable is one with a value of true or false. Here are examples:
image
Notice that the words true and false do not need to be enclosed in quotes. This is because they are literal values that JavaScript recognizes.
Boolean variables are useful when you need variables that can only have values of true and false, such as in event handlers (covered in Chapter 7).
NOTE
image
When we talk about the concept of a Boolean variable, the first letter of the word Boolean is capitalized (because it is derived from the name of the mathematician George Boole). However, the JavaScript reserved word boolean is written in all lowercase letters when you use the keyword in a script.
Null
Null is used to indicate an empty object (you will learn about objects in Chapter 9). If you need to define an object with a value of null, use a declaration like this:
image
As with the Boolean variables, you do not need to enclose this value in quotation marks as you do with string values, because JavaScript recognizes the special value of null. The null data type can only have one value: null.
Undefined
The undefined data type is similar to null, in that it only has one possible value: undefined. This value occurs when a variable has not been assigned an initial value, or when a previously undeclared variable is used. For example, both of the following examples make use of undefined variables (you will see more on how to use variables later in this chapter):
image
Ask the Expert
Q:  Why do I need to learn about variables? Couldn’t I just put in the number or text I want to use right where I’m going to use it?
A:  You can do that; however, it will make longer scripts much harder to write, read, and debug. It also makes it much more difficult to update your scripts because, in order to change that number or text, you would need to change every line where it appears. When you use variables, you can modify just one line of code to change the value of a variable every place it is used. As you gain more experience with JavaScript, you will see just how useful variables are.
Q:  Why don’t I need to define the type of number I am using (such as float or integer) when I declare a numeric variable?
A:  JavaScript doesn’t require this, which can be a good or bad feature depending on your perspective. To JavaScript, any number is just a number and can be used as a number variable.
Q:  Why do I need to put quotation marks around the text in a string?
A:  This is done so that JavaScript knows where a string begins and ends. Without it, JavaScript would be unsure what should be in a string and what should not.
Q:  But doesn’t a semicolon end a statement? Why not use that and lose the quote marks?
A:  A variable declaration or any command involving strings can become more complex when the addition operator is used to add two strings and/or variables together. When this happens, JavaScript needs to know when one string stops and another begins on the same line.
Q:  What does the backslash () character do, in general?
A:  If the backslash is followed by a code to create a special character, the special character is rendered in its place. Otherwise, the first character after a single backslash is seen “as-is” by JavaScript and treated as part of the string in which it resides.
Try This 3-1 Declare Variables
image
This project gives you the opportunity to practice declaring variables with various values. It also prints a short line of text on the page.
Step by Step
1.  Create an HTML page, leaving the space between the <body> and </body> tags open.
2.  Between the <body> and </body> tags, add the <script> and </script> tags as you learned in Chapter 2.
3.  Create a numeric variable named chipscost and give it the value 2.59.
4.  Create a Boolean variable named istrue and give it the value false.
5.  Create a variable named nada and give it the value null.
6.  Create a JavaScript statement to write to the Web page the string value that follows. Remember to escape quotation marks when necessary:
John said, “This project is fun!”
7.  The body section of the HTML document should look like this when you are finished:
image
8.  Save the file as pr3_1.html and view it in your Web browser.
You should see only the text that you output with the document.write() command. The variable definitions won’t be printed on the browser screen. You can view the page source code to see how the variable definitions look in the code.
Try This Summary
In this project, you were able to use your skills to declare different types of variables in a script. This project included a numeric variable, a Boolean variable, and a variable with a value of null. You were also able to use skills learned in Chapter 2 to write a line of text to the page with JavaScript.
image
Using Variables in Scripts
To make a variable useful, you need to do more than just declare it in the script. You need to use it later in the script in some way, perhaps to print its value or even just to change its value. To use a variable, you make the call to a variable after it has been declared.
Making a Call to a Variable
The following code shows how to write the value of a variable to a Web page using the document.write() method:
image
The script begins by declaring a variable mycar and giving it a value of “Corvette”. Then, in the document.write() command, you see that just the variable name mycar is enclosed within the parentheses. The result of this script is simply to write “Corvette” to the browser.
There are no quotation marks around the mycar variable that is being written to the page. The reason for this is that the mycar variable has already been given a string value, so it does not need to be within quotes to print its value to the page in the document.write() command. Already, you can see how using a variable has the advantage of making a short document.write() command easier to code.
Adding Variables to Text Strings
The preceding code just prints the value of the variable in the browser. If you want that variable to print along with some other text in a string, the document.write() command becomes more complex. The text string needs quotes around it if it has not been defined as a variable, and the variable needs to be on its own. You use the addition operator (+) to add the value of the variable to the string, as shown in this example:
image
This code prints the following sentence in the browser window:
image
Notice the space after the word “my” in the code. This ensures that a space appears before the variable is added to the string. If you used the line
image
the result would be
image
When adding strings, you need to be careful to add the spaces that you want to appear in the output.
The addition operator enables you to place a variable before, after, or even into the middle of a string. To insert a variable into the middle of a string (so that it shows with text on both sides of it), just use another addition operator to add whatever you need to the right of the variable, as in this example:
image
Now the variable sits inside two text strings, putting a single string together from three pieces. This code prints the following sentence to the browser:
image
When using the variable, you need to make sure that the variable and addition operators are not inside the quotation marks of a string. If they are, you will not get the results you intended. For example, look at this code:
image
JavaScript will not recognize the operators and variables here; they are seen only as part of the text string because they are inside the quotes. Instead of using the variable, JavaScript takes everything literally and prints this sentence in the browser:
image
To make this code easier to write, you could place every string involved into a variable, so that you only need to add the variable values together rather than dealing with the quotes, like this:
image
This prints the same sentence but allows you to change its parts later without needing to edit the document.write() command.
The techniques you’ve learned in this section will become useful as your strings become more complex, especially when you use HTML code within the strings.
Writing a Page of JavaScript
Now that you know how to use variables and write basic HTML code to the page using JavaScript, you will create a page that is almost entirely written with JavaScript (everything inside the <body> and </body> tags), as a way to reinforce the techniques you have learned up to this point.
Creating the Framework
The first thing you need is a basic framework for the page so that you know where to insert your script. Since you are writing information onto the page, the script tags will be placed within the <body> and </body> tags. In this case, an external script file named ch3_code.js will be used. The body section of your HTML document will look like this:
image
The code you place in the ch3_code.js file will determine what shows up in the browser when you have finished.
Defining the Variables
To begin your script file, use some JavaScript code to write an HTML heading. You could write the code as a string directly into the document.write() command, as shown here:
image
On the other hand, you could place the string inside a variable and use the variable inside the document.write() command later in the script:
image
For this example, you will go with the second method, since it uses a variable. You will see how this can be a handy feature as you get further into the script.
In fact, along with the headingtext variable, you’ll create a bunch of variables to hold the strings of HTML code to add to the page. The next one will add a short sentence of introduction to the page. The variable declaration for the introduction will look like this:
image
Next, you’ll add a link to the page. The variable declaration for the link looks like this:
image
Next, you’ll put in some red text to add a little color. Here’s the redtext variable definition:
image
Finally, you’ll add in some variables that give you just the opening and closing strong tags and paragraph tags:
image
The code for all of the variables in the ch3_code.js file is as follows:
image
Adding the Commands
Now, following the variable declarations, you can add some document.write() commands to the ch3_code.js file to write the contents of the variables back to the HTML document:
image
This writes the heading at the top of the page. Adding the begineffect and endeffect variables to the left and right of the myintro variable writes the introductory text in bold under the heading. After that is a new paragraph with a link, and then another new paragraph with the red text message.
Here is the entire code for the ch3_code.js file up to this point:
image
Save the ch3_code.js file and then load your HTML document. The end result of this code in the browser is shown in Figure 3-1. Note the strong introduction text and the use of paragraphs between sections.
image
image
Figure 3-1  The result of the JavaScript code in a Web browser
Modifying the Page
Now suppose that you do not like the layout as it appeared on the Web page. Instead, you want the strongly emphasized introduction to be normally emphasized. If you had written the document.write() commands with plain strings rather than variables, you would need to search through the code to find the <strong></strong> tags and change them to <em></em> tags.
However, since you used the variables, all you need to do is change the values of the appropriate variables at the top of the script file rather than looking for the strong tags inside a bunch of code.
The code that follows shows the changes that you could make to the script file to get the new effect. Notice how you only need to change the values of the begineffect and endeffect variables to change the format of the text on the page:
image
Save the ch3_code.js file and reload your HTML document. Figure 3-2 shows how these changes affect the display of the page in a Web browser.
image
image
Figure 3-2  The page after changing some JavaScript variables
Try This 3-2 Create an HTML Page with JavaScript
image
In this project, you will create an HTML page with JavaScript, similar to the one you created in this chapter. The variables will be given new values, and the differences should be noticeable.
Step by Step
  1.  Create an HTML page, leaving the space between the <body> and </body> tags open.
  2.  Between the <body> and </body> tags, add the <script> and </script> tags to link to a file named prjs3_2.js. Save the HTML file as pr3_2.html.
  3.  Open a file to use as your JavaScript file. Save it with the filename prjs3_2.js. Use this file to add the JavaScript code in steps 4–10.
  4.  Create a variable named myheading and give it this value:
This is My Web Page!
  5.  Create a variable named linktag and give it this value:
<a href=“http://www.webxpertz.net”>Web Site Link!</a>
  6.  Create a variable named sometext and give it this value:
This text can be affected by other statements.
  7.  Create a variable named begineffect and give it the value <em>.
  8.  Create a variable named endeffect and give it the value </em>.
  9.  Create a variable named beginpara and give it the value <p>.
10.  Create a variable named endpara and give it the value </p>.
11.  Place all of the variable definitions into a single var statement so that you do not need to keep repeating the var keyword (remember to end the last one with a semicolon).
12.  Write the value of each variable back to the HTML document in this order:
myheading
begineffect
sometext
endeffect
beginpara
linktag
endpara
beginpara
sometext
endpara
When you have finished, save the prjs3_2.js file. It should look like this:
image
13.  Open the pr3_2.html page in your Web browser and view the results.
14.  Reopen the prjs3_2.js file and make the changes in steps 15–16.
15.  Change the value of begineffect to <strong>.
16.  Change the value of endeffect to </strong>.
17.  When you have finished, save the prjs3_2.js file. It should look like this:
image
18.  Reload the pr3_2.html page in your Web browser. Notice the differences resulting from the changes in the variable values in the JavaScript file.
Try This Summary
In this project, you combined your new skills in using variables with earlier skills in writing to a Web page with JavaScript. You created a Web page with a script that uses variables to write the HTML code on the page. You then changed the values of two variables and resaved the script file. The changes to the variables made visible changes to the page.
image
image
Chapter 3 Self Test
image
  1.  A variable __________ or __________ a value.
  2.  What are two of the benefits of using variables?
A.  They can save you time in writing and updating your scripts, and they can make the purpose of your code clearer.
B.  They make the purpose of your code clearer, and they make it harder for noncoders to understand the script.
C.  They can save you time in writing and updating your scripts, and they make it harder for noncoders to understand the script.
D.  They offer no advantages whatsoever.
  3.  To declare a variable, you use the __________ keyword.
  4.  What symbol is used as the assignment operator in JavaScript?
A.  +
B.  –
C.  :
D.  =
  5.  Which of the following declares a variable named pagenumber and gives it a value of 240?
A.  var PageNumber=240;
B.  pagenumber=220;
C.  var pagenumber=240;
D.  int named Pagenumber=240;
  6.  Variable names are not case sensitive.
A.  True
B.  False
  7.  A variable name must begin with a(n) __________, a(n) __________, or a(n) __________ character.
  8.  You should avoid using JavaScript keywords and reserved words as variable names.
A.  True
B.  False
  9.  Which of the following variable declarations uses a variable with a valid variable name in JavaScript?
A.  var return;
B.  var my_house;
C.  var my dog;
D.  var 2cats;
10.  In JavaScript, the data __________ include number, string, Boolean, null, and undefined.
11.  To denote an exponent in JavaScript, you use a letter __________ right after the base number and before the exponent.
12.  Which of the following string declarations is invalid?
A.  var mytext = “Here is some text!”;
B.  var mytext = ‘Here is some text!’;
C.  var mytext = “Here is some text!’;
D.  var mytext = “Here is some text!”;
13.  Which of the following statements would be valid in JavaScript?
A.  document.write(“John said, “Hi!””);
B.  document.write(‘John said, “Hi!””);
C.  document.write(“John said, “Hi!’”);
D.  document.write(“John said, “Hi!””);
14.  __________ characters enable you to add things to your strings that could not be added otherwise.
15.  Which of the following successfully displays the value of a variable named myhobby by adding it to a string?
A.  document.write(“I like to +myhobby+ every weekend”);
B.  document.write(“I like to ” +myhobby+ “ every weekend”);
C.  document.write(“I like to myhobby every weekend”);
D.  document.write(“I like to ‘myhobby’ every weekend”);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.90.235