Java Reference
In-Depth Information
To demonstrate that you can use expressions in places you'd use numbers or variables, you show the
results of the calculation of 15/10 directly by including it in the alert() function.
alert(15 / 10);
Finally, you do the same calculation, but this time using the two variables firstNumber , which was set
to 15 , and secondNumber , which was set to 10 . You have the expression firstNumber / secondNum-
ber , the result of which you store in our answer variable. Then, to prove it has all worked, you show
the value contained in answer by using your friend the alert() function.
answer = firstNumber / secondNumber;
alert(answer);
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 you might as well program in the result of the calculation, rather
than force JavaScript to calculate it for you. For example, rather than writing 15 / 10, you might as well
just write 1.5. After all, the more calculations you force JavaScript to do, 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 you'll be looking at here are the increment and decrement operators, which
are represented by two plus signs ( ++ ) and two minus signs ( -- ), respectively. Basically, all they do is
increase or decrease a variable's value by one. You could use the normal + and - operators to do this, for
example:
myVariable = myVariable + 1;
myVariable = myVariable - 1;
You 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. When 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 Chapter 3, when you look at how you can run the same code a number of times, you'll see that these
operators are very useful and widely used. In fact, the ++ operator is so widely used it has a computer
language named after it: C++. The joke here is that C++ is one up from C. (Well, that's programmer
humor for you!)
Search WWH ::




Custom Search