Java Reference
In-Depth Information
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 because
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 from your understanding of mathematics. The way
JavaScript does the calculation is to first calculate
1 * 2
=
2
, and then use this result in the
addition, so that JavaScript finishes 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 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.
Fahrenheit to Centigrade
trY it out
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 _ example4.html
:
<!DOCTYPE html>
<html lang
=
"en">
<head>
<title>Chapter 2, Example 4</title>
</head>
<body>
<script>
// Equation is °C
=
5/9 (°F - 32).
var degFahren
=
prompt("Enter the degrees in Fahrenheit",50);
var degCent;
degCent
=
5/9 * (degFahren - 32);
alert(degCent);
</script>
</body>
</html>
If you load the page into your browser, you should see a prompt box, like that shown in
Figure 2-3, 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 see what results you get. For example,
change the value to
32
and reload the page. This time you should see 0 appear in the box.