Java Reference
In-Depth Information
Using Data — Calculations and Basic String
Manipulation
Now that you've seen how to cope with errors, you can get back to the main subject of this chapter: data
and how to use them. You've seen how to declare variables and how they can store information, but so
far you haven't done anything really useful with this knowledge — so just why would you want to use
variables at all?
What variables enable you to do is temporarily hold information that you can use for processing in
mathematical calculations, in building up text messages, or in 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 fi nances. You might fi rst add up all the money you needed to spend, and then
store it in temporary memory. After you had added up all your money coming in, you could deduct
the amount stored in the memory to fi gure out how much would be left over. Variables can be used in
a similar way: You can fi rst gain the necessary user input and store it in variables, and then you can do
your calculations using the values obtained.
In this section you'll see how you 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: plus ( + ), minus ( - ), star ( * ),
and forward slash ( / ), respectively. These symbols are called operators because they operate on the val-
ues you 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.
Imagine you were calculating the total value of items on a shopping list. You could write this calcula-
tion as follows:
Total cost of shopping = 10 + 5 + 5
Or, if you actually calculate the sum, it's
Total cost of shopping = 20
Now let's see how to do this in JavaScript. In actual fact, it is very similar except that you need to use a
variable to store the fi nal total.
var TotalCostOfShopping;
TotalCostOfShopping = 10 + 5 + 5;
alert(TotalCostOfShopping);
First, you declare a variable, TotalCostOfShopping , to hold the total cost.
In the second line, you have the code 10 + 5 + 5 . This piece of code is known as an expression . When
you assign the variable TotalCostOfShopping the value of this expression, JavaScript automatically
Search WWH ::




Custom Search