Java Reference
In-Depth Information
You 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
You've seen 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 this point.
var myVariable;
myVariable = 1 + 1 * 2;
alert(myVariable);
If you were to type this, 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 fi nd 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 from your understanding of mathematics. The way
JavaScript does the calculation is to fi rst calculate 1 * 2 = 2, and then use this result in the addition, so
that JavaScript fi nishes off with 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 fi rst? 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
Take a look at a slightly more complex example — a Fahrenheit to centigrade converter. (Centigrade is
another name for the Celsius temperature scale.) Type this code and save it as ch2_examp4.htm:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<body>
Search WWH ::




Custom Search