Java Reference
In-Depth Information
calculates the value of the expression (20) and stores it in the variable. Notice that the equals sign tells
JavaScript to store the results of the calculation in the TotalCostOfShopping variable. This is called
assigning the value of the calculation to the variable, which is why the single equals sign (=) is called the
assignment operator .
Finally, you display the value of the variable in an alert box.
The operators for subtraction and multiplication work in exactly the same way. Division is a little
different.
Try It Out Calculations
Let's take a look at an example using the division operator to see how it works.
1. Enter the following code and save it as ch2_examp3.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>
<script language=”JavaScript” type=”text/javascript”>
var firstNumber = 15;
var secondNumber = 10;
var answer;
answer = 15 / 10;
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 con-
taining the value 1.5. These values are the results of three calculations.
3. The fi rst thing you do in the script block is declare your three variables and assign the fi rst two
of these variables 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.
Search WWH ::




Custom Search