Java Reference
In-Depth Information
alert(answer);
alert(15 / 10);
answer
=
firstNumber / secondNumber;
alert(answer);
</script>
</body>
</html>
2.
Load this into your web browser. You should see a succession of three
alert
boxes, each
containing the value
1.5
. These values are the results of three calculations.
3.
The first thing you do in the script block is declare your three variables and assign the first two of
them values that you'll be using later:
var firstNumber
=
15;
var secondNumber
=
10;
var answer;
4.
Next, you set the
answer
variable to the results of the calculation of the expression
15/10
. You
show the value of this variable in an
alert
box:
answer
=
15 / 10;
alert(answer);
This example demonstrates one way of doing the calculation, but in reality you'd almost never do
it this way.
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 /
secondNumber
, the result of which you store in your
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);
You'll do most calculations 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.