Java Reference
In-Depth Information
(+), minus ( ), star ( * ), and forward slash ( / ), respectively. These symbols are called operators
because they operate on the values you give them. In other words, they perform some calculation or
operation and return a result. You can use the results of these calculations almost anywhere you'd
use a number or a variable.
Imagine you were calculating the total value of items on a shopping list. You could write this
calculation as follows:
Total cost of shopping = 10 + 5 + 5
Or, if you actually calculate the sum, it's:
Total cost of shopping = 20
Now let's see how to do this in JavaScript. In actual fact, it is very similar except that you need to
use a variable to store the final total:
var totalCostOfShopping;
totalCostOfShopping = 10 + 5 + 5;
alert(totalCostOfShopping);
First, you declare a variable, totalCostOfShopping , to hold the total cost.
In the second line, you have the code 10 + 5 + 5 . This piece of code is known as an expression .
When you assign the variable totalCostOfShopping the value of this expression, JavaScript
automatically 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.
Calculations
trY it out
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_example3.html :
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Chapter 2, Example 3</title>
</head>
<body>
<script>
var firstNumber = 15;
var secondNumber = 10;
var answer;
answer = 15 / 10;
Search WWH ::




Custom Search