Now that we've seen how to cope with errors, we can get back to the main subject of this chapter: data and how to use it. We've seen how to declare variables and how they can store information, but so far we haven't done anything really useful with this—so just why would we want to use variables at all?
What variables allow us to do is temporarily hold information that we can use for processing in mathematical calculations, in building up text messages, or processing words that the user has entered. Variables are a little bit like the memory store button on the average pocket calculator. Say you were adding up your finances. You might first add up all the money you needed to spend, and then store it in temporary memory. Once you had added up all your money coming in, you could deduct the amount stored in the memory to figure out how much is left over. Variables can be used in a similar way; we can first gain the necessary user input and store it in variables, then we can do our calculations using the values obtained.
In this section, we'll see how we can put the values stored in variables to good use in both number-crunching and text-based operations.
Let's imagine we were calculating the total value of items on a shopping list. We could write this calculation as
Total cost of shopping = 10 + 5 + 5
or, if we actually calculate the sum, it's
Total cost of shopping = 20
var TotalCostOfShopping; TotalCostOfShopping = 10 + 5 + 5; alert(TotalCostOfShopping);
Finally, we display the value of the variable in an alert box.
The other operators for subtraction and multiplication, – and *, work in exactly the same way. Division is a little different and is represented by the forward slash character /.
Let's take a look at an example using the division operator to see how it works. Type in the following code and save it as ch2_examp3.htm.
Load this into your web browser. You should see a succession of three alert boxes, each containing the value 1.5. These values are the results of three calculations.
The first thing we do in the script block is to declare our three variables and assign the first two of these variables with values that we'll be using later.
var firstNumber = 15; var secondNumber = 10; var answer;
Next, we set the answer variable to the results of the calculation of the expression 15/10. We show the value of this variable in an alert box.
If you're thinking, "why not just set the answer variable to 1.5," then I agree with you. This example demonstrates one way of doing the calculation, but in reality you'd almost never do it this way.
To demonstrate that we can use expressions in places we'd use numbers or variables, we show the results of the calculation of 15/10 directly by including it in the alert() function.
alert(15 / 10);
Finally we do the same calculation, but this time using our two variables firstNumber, which was set to 15, and secondNumber, which was set to 10. We have the expression firstNumber / secondNumber, the result of which we store in our answer variable. Then, to prove it has all worked, we show the value contained in answer by using our friend the alert() function.
answer = firstNumber / secondNumber; alert(answer);
Another reason for using the result rather than the calculation is that it makes code more readable. Which would you prefer to read in code, 1.5 * 45 – 56 / 67 + 2.567, or 69.231? Still better, a variable named, for example, PricePerKG, makes code even easier to understand for someone not familiar with it.
A number of operations using the math operators are so commonly used that they have been given their own operators. The two we'll be looking at here are the increment and decrement operators, which are represented by ++ and —. Basically, all they do is increase or decrease a variable's value by one. We could use the normal + and – operators to do this, for example:
myVariable = myVariable + 1; myVariable = myVariable – 1;
(Note that we can assign a variable a new value that is the result of an expression involving its previous value.) However using the increment and decrement operators shortens this to
The result is the same—the value of myVariable is increased or decreased by one—but the code is shorter. Once you are familiar with the syntax, this becomes very clear and easy to read.
Right now, you may well be thinking that these operators sound as useful as a poke in the eye. However, in the next chapter when we look at how we can run the same code a number of times, we'll see that these operators are very useful and widely used. In fact, the ++ operator is so widely used it has computer language after it, C++. The "joke" here is that C++ is one up from C (well, that's programmer humor for you!).
As well as placing the ++ or — after the variable, we can also place it before, like so:
When the ++ and – are used on their own, it makes no difference where they are placed, but while the increment and decrement operators are usually used on their own, it is possible to use the ++ and — operators in an expression along with other operators. For example,
myVar = myNumber++ - 20;
takes 20 away from myNumber and then increments the variable myNumber by one, before assigning the result to the variable myVar. If instead we placed the ++ before, and prefixed it like this:
myVar = ++myNumber - 20;
first myNumber is incremented by one, and then myNumber has 20 subtracted from it. It's a subtle difference but in some situations a very important one. Take the following code:
myNumber = 1; myVar = (myNumber++ * 10 + 1);
What value will myVar contain? Well, because the ++ is postfix (it's after the myNumber variable), it will be incremented afterwards. So the equation reads: myNumber times 10 plus one and then increment myNumber by one.
myVar = 1 * 10 + 1 = 11
Then add one to myNumber to get 12, but this is done after the value 11 has been assigned to myVar. Now take a look at the following code:
myNumber = 1; myVar = (++myNumber * 10 + 1);
This time myNumber is incremented by one first, then times 10 and plus one.
myVar = 2 * 10 + 1 = 21
As you can imagine such subtlety can easily be overlooked and lead to bugs in code; therefore, it's usually best to avoid this syntax.
Before we go on, this seems to be a good point to introduce another operator, +=. This operator can be used as a shortcut for increasing the value held by a variable by a set amount. For example,
myVar += 6;
does exactly the same thing as
We can also do the same thing for subtraction and multiplication, as shown here:
myVar -= 6; myVar *= 6;
which is equivalent to
myVar = myVar – 6; myVar = myVar * 6;
We saw that symbols that perform some function—like +, which adds two numbers together and -, which subtracts one number from another—are called operators. Unlike people, not all operators are created equal; some have a higher precedence—that is, they get dealt with sooner. A quick look at a simple example will help demonstrate my point.
Why? Because * has a higher precedence than +. The = symbol, also an operator (called the assignment operator), has the lowest precedence—it always gets left until last.
Let's take a look at a more complex example—a Fahrenheit to centigrade converter. (Centigrade is another name for the Celsius temperature scale.) Type in this code and save it as ch2_examp4.htm.
If you load the page into your browser, you should see a prompt box, like that shown in Figure 2-11, that asks you to enter the degrees in Fahrenheit to be converted. The value 50 is already filled in by default.
If you leave it at 50 and click OK, an alert box with the number "10" in it appears. This represents 50 degrees Fahrenheit converted to centigrade.
Reload the page and try changing the value in the prompt box to different values to see what results you get. For example, change the value to 32 and reload the page. This time you should see "0" appear.
The first line of the script block is a comment since it starts with two forward slashes (//). It contains the equation for converting Fahrenheit temperatures to centigrade and is in the example code solely for reference.
// Equation is °C = 5/9 (°F - 32).
We pass two pieces of information to the prompt() function:
The text to be displayed—usually a question that prompts the user for input
The default value that is contained in the input box when the prompt dialog first appears
These two pieces of information must be specified in the given order and separated by a comma. If you don't want a default value to be contained in the input box when the prompt box opens, you should use an empty string ("") for the second piece of information.
As you can see in the preceding code, our text is "Enter the degrees in Fahrenheit," and the default value in the input box is 50.
degCent = 5/9 * (degFahren - 32);
What if we didn't use the parentheses? Then our code would be
degCent = 5/9 * degFahren - 32;
Finally, in our script block, we display the answer using the alert() function.
In an earlier section, we looked at the text or string data type, as well as numerical data. Just as numerical data has associated operators, strings have operators too. In this section we'll introduce some basic string manipulation techniques using such operators. We'll be covering strings in more depth in Chapter 4 and looking at advanced string handling in Chapter 8.
var concatString = "Hello " + "Paul";
The string now stored in the variable concatString is "Hello Paul". Notice that the last character of the string "Hello " is a space—if we left this out, our concatenated string would be "HelloPaul".
Let's look at an example using the + operator for string concatenation. Type the following code in and save it as ch2_examp5.htm.
If you load it into your web browser, you should see a prompt box asking for your name.
We start the script block by declaring three variables. We set the first variable, greetingString, to a string value. The second variable, myName, is assigned to whatever is entered by the user in the prompt box. We do not initialize the third variable, concatString, here. It will be used to store the result of the concatenation that we'll do later in the code.
var greetingString = "Hello"; var myName = prompt("Please enter your name", ""); var concatString;
In the last chapter, we saw how the web page was represented by the concept of a document and that it had a number of different properties, such as the bgColor. We can also use document to write text and HTML directly into the page itself. We do this by using the word document, followed by a dot, and then write(). We then use document.write() much as we do the alert() function, in that we put the text that we want displayed in the web page inside the parentheses following the word write. Don't worry too much about this here though, because it will all be explained in detail in Chapter 4. However, we now make use of document.write() in our code to write the result of an expression to the page.
document.write(greetingString + " " + myName + "<br>");
The expression written to the page is the concatenation of the value of the greetingString variable, a space (" "), the value of the myName variable, and the HTML <br> tag, which causes a line break. For example, if I enter "Paul" into the prompt box, the value of this expression will be
In the next line of code we have a similar expression. This time it is just the concatenation of the value in the variable greetingString, a space, and the value in the variable myName. We store the result of this expression in the variable concatString. Finally, we write the contents of the variable concatString to the page using document.write().
concatString = greetingString + " " + myName; document.write(concatString);
What if we want to mix text and numbers in an expression? A prime example of this would be in the temperature converter we saw earlier. In the example, we just display the number without telling the user what it actually means. What we really want to do is display the number with descriptive text wrapped around it, such as "The value converted to degrees centigrade is 10."
alert("My age is " + 101);
We can try out this technique of concatenating strings and numbers in our temperature converter example. We'll output some explanatory text, along with the result of the conversion calculation. The changes that we need to make are very small, so load ch2_examp4.htm into your text editor and change the line shown below. Then save it as ch2_examp6.htm.
Load the page into your web browser. Click OK in the prompt box to submit the value 50, and this time you should see the box shown in Figure 2-12.
This example is identical to ch2_examp4.htm, except for one line:
alert(degFahren + "\xB0 Fahrenheit is " + degCent + "\xB0 centigrade");
Something to be aware of when using special characters is they are not necessarily cross-platform-compatible. While we can use \xNN for a certain character on a Windows computer, we may find we need to use a different character on a Mac or a Unix machine to achieve the same look. We'll see in Chapter 5 how we can detect what operating system a user has and use this information to make sure our code works with different operating systems.
We'll be looking at more string manipulation techniques in Chapter 4—we'll see how to search strings and insert characters in the middle of them, and in Chapter 8 we'll be seeing some very sophisticated string techniques.