﻿ Using Data - Calculations and Basic String Manipulation

JavaScript Validator     JavaScript Editor ﻿

## Using Data—Calculations and Basic String Manipulation

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.

### Numerical Calculations

JavaScript has a range of basic mathematical capabilities, such as addition, subtraction, multiplication, and division. Each of the basic math functions is represented by a symbol: +, -, *, and /, respectively. We call these symbols operators because they operate on the values we give them. In other words, they perform some calculation or operation and return a result to us. You can use the results of these calculations almost anywhere you'd use a number or a variable.

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

Now let's see how we would do this in JavaScript. In actual fact, it is very similar except that we need to use a variable to store the final total.

```var TotalCostOfShopping;
TotalCostOfShopping = 10 + 5 + 5;
```

First, we declared a variable, TotalCostOfShopping, to hold the total cost.

In the second line we have the code 10 + 5 + 5. This piece of code is known as an expression. When we assign the variable TotalCostOfShopping with the value of this expression, JavaScript automatically calculates the value of the expression (20) and stores it in the variable. You'll notice that we've used the = sign to tell JavaScript to store the results of the calculation in the TotalCostOfShopping variable. We call this assigning the value of the calculation to the variable, which is why the single equals sign (=) is called the assignment operator.

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

#### Try It Out – Calculations

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.

```<html>
<body>

<script language="JavaScript" type="text/javascript">
var firstNumber = 15;
var secondNumber = 10;

</script>

</body>
</html>
```

#### How It Works

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;
```

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.

```answer = 15 / 10;
```

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;
```

Most calculations will be done in the third way; that is, using variables, or numbers and variables, and storing the result in another variable. The reason for this is that if the calculation used literal values (actual values, such as 15 / 10), then we might as well program in the result of the calculation, rather than force JavaScript to calculate it for us. For example, rather than writing 15 / 10, we might as well just write 1.5. After all, the more calculations we force JavaScript to do, the more work it has to do and the slower it will be, though admittedly just one calculation won't tax it too much.

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.

#### Increment and Decrement Operators

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

```myVariable++;
myVariable--;
```

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:

```++myVariable;
--myVariable;
```

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

```myVar = myVar + 6;
```

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;
```

### Operator Precedence

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.

```<html>
<body>

<script language="JavaScript" type="text/javascript">

var myVariable;

myVariable = 1 + 1 * 2;

</script>

</body>
</html>
```

If you were to type this in, what result would you expect the alert box to show as the value of myVariable? You might expect that since 1 + 1 = 2 and 2 * 2 = 4, the answer is 4. Actually, you'll find that the alert box shows 3 as the value stored in myVariable as a result of the calculation. So what gives? Doesn't JavaScript add up right?

Well, you probably already know the reason why from your understanding of mathematics. The way JavaScript does our calculation is to first calculate 1 * 2 = 2, and then use this result in the addition, so that JavaScript finishes off by doing 1 + 2 = 3.

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.

The + and operators have an equal precedence, so which one gets done first? Well, JavaScript works from left to right, so if operators with equal precedence exist in a calculation, they get calculated in the order in which they appear when going from left to right. The same applies to * and /, which are also of equal precedence.

#### Try It Out – Fahrenheit to Centigrade

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.

```<html>
<body>

<script language="JavaScript" type="text/javascript">
// Equation is °C = 5/9 (°F - 32).
var degFahren = prompt("Enter the degrees in Fahrenheit",50);
var degCent;

degCent = 5/9 * (degFahren - 32);

</script>

</body>
</html>
```

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.

#### How It Works

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

Our task is to represent this equation in JavaScript code. We start by declaring our variables, degFahren and degCent.

```var degFahren = prompt("Enter the degrees in Fahrenheit",50);
var degCent;
```

Instead of initializing the degFahren variable to a literal value, we get a value from the user using the prompt() function. The prompt() function works in a similar way to an alert() function, except that as well as displaying a message, it also contains a text box in which the user can enter a value. It is this value that will be stored inside the degFahren variable. The value returned is a text string but this will be implicitly converted by JavaScript to a number when we use it as a number, as discussed in the section on data type conversion later in this chapter.

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.

Next in our script block comes the equation represented in JavaScript. We store the result of the equation in the degCent variable. You can see that the JavaScript looks very much like the equation we have in the comment, except we use degFahren instead of °F, and degCent rather than °C.

```degCent = 5/9 * (degFahren - 32);
```

The calculation of the expression on the right-hand side of the equals sign raises a number of important points. First, just as in math, the JavaScript equation is read from left to right, at least for the basic math functions like +, -, and so on. Secondly, as we saw earlier, just as there is precedence in math, so there is too in JavaScript.

Starting from the left, first JavaScript works out 5/9 = .5556 (approximately). Then it comes to the multiplication, but wait . . . the last bit of our equation, degFahren – 32, is in parentheses. This raises the order of precedence and causes JavaScript to calculate the result of degFahren – 32 before doing the multiplication. For example, when degFahren is set to 50, (degFahren - 32) = (50 – 32) = 18. Now JavaScript does the multiplication, .5555 * 18, which is 10.

What if we didn't use the parentheses? Then our code would be

`degCent = 5/9 * degFahren - 32;`

The calculation of 5/9 remains the same, but then JavaScript would have calculated the multiplication, 5/9 * degFahren. This is because the multiplication takes precedence over the subtraction. When degFahren is 50, this equates to 5/9 * 50 = 27.7778. Finally JavaScript would have subtracted the 32, leaving the result as –4.2221; not the answer we want!

Finally, in our script block, we display the answer using the alert() function.

```alert(degCent);
```

That concludes our brief look at basic calculations with JavaScript. However, in Chapter 4 we'll be looking at something called the Math object, which enables us to do more complex calculations such as finding cosines, square roots, and much more.

### Basic String Operations

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.

One thing you'll find yourself doing again and again in JavaScript is joining two strings together to make one string—a process that's termed concatenation. For example, we may want to concatenate the two strings "Hello " and "Paul" to make the string "Hello Paul". So how do we concatenate? Easy! We use the + operator. Recall that when applied to numbers, the + operator adds them up, but when used in the context of two strings, it joins them together.

```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".

#### Try It Out – Concatenating Strings

Let's look at an example using the + operator for string concatenation. Type the following code in and save it as ch2_examp5.htm.

```<html>
<body>

<script language="JavaScript" type="text/javascript">

var greetingString = "Hello";
var concatString;

document.write(greetingString + " " + myName + "<br>");

concatString = greetingString + " " + myName;

document.write(concatString);

</script>

</body>
</html>
```

Enter your name and click OK. You should see a greeting and your name displayed twice on the web page.

#### How It Works

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

`Hello Paul<br>`

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);
```

### Mixing Numbers and Strings

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

Mixing numbers and text is actually very easy. We can simply join them together using the + operator. JavaScript is intelligent enough to know that when both a string and a number are involved, we're not trying to do numerical calculations, but rather we want to treat the number as a string and join it to the text. For example, to join the text My age is and the number 101 together, we could simply do the following:

```alert("My age is " + 101);
```

This would produce an alert box with "My age is 101" inside it.

#### Try It Out – Making the Temperature Converter User-Friendly

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.

```<html>
<body>

<script language="JavaScript" type="text/javascript">

// Equation is °C = 5/9 (°F - 32).

var degFahren = prompt("Enter the degrees in Fahrenheit",50);
var degCent;

degCent = 5/9 * (degFahren - 32);

</script>

</body>
</html>```

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.

#### How It Works

This example is identical to ch2_examp4.htm, except for one line:

```alert(degFahren + "\xB0 Fahrenheit is " + degCent + "\xB0 centigrade");
```

so we will just look at this line here. You can see that the alert() function contains an expression. Let's look at that expression more closely.

First we have the variable degFahren, which contains numerical data. We concatenate that to a string "\xBO Fahrenheit is ". JavaScript realizes that because you are adding a number and a string, you want to join them together into one string rather than trying to take their sum, and so automatically converts the number contained in degFahren to a string. We next concatenate this string to the variable degCent, containing numerical data. Again JavaScript converts the value of this variable to a string. Finally we concatenate to the string "\xBO centigrade".

Note also that we have used an escape sequence to insert the degree character in the strings. You'll remember from earlier in the chapter that \xNN can be used to insert special characters not available to type in directly. Remember NN are hexadecimal numbers representing a character from the Latin-1 character table (see Appendix D for more details). So, when JavaScript spots \xB0 in a string, instead of showing those characters, it does a lookup to see what character is represented by B0 and shows that instead.

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.

JavaScript Validator     JavaScript Editor