HTML and CSS Reference
In-Depth Information
Working with Operators and Operands
In the previous session, you worked with Date objects to display specified dates and
times on a Web page. In this session, you'll learn how to perform calculations with dates
and JavaScript variables. To perform a calculation, you need to insert a JavaScript state-
ment that contains an operator. An operator is a symbol used to act upon an item or a
variable within an expression. The variables or expressions that operators act upon are
called operands . An operator is a very basic concept. In fact, you've been using opera-
tors throughout this and the previous tutorial. You've been using the + operator to com-
bine text strings and add numeric values. For example, the following statement from the
showDate() function uses the + operator along with the getMonth() method to increase
the month number value by 1:
thisMonth = dateObj.getMonth() + 1;
You have also used the + operator to combine text strings, as in the following state-
ment from the showDate() function, which displays dates in the month/day/year format:
thisMonth + “/” + thisDate + “/” + thisYear;
Using Arithmetic and Unary Operators
The + operator belongs to a group of operators called arithmetic operators that perform
simple mathematical calculations. Figure 11-13 lists some of the arithmetic operators
and gives examples of how they work.
Figure 11-13
arithmetic operators
Operator
Description
Example
+
Combines or adds two items
Men = 20;
Women = 25;
Total = Men + Women;
-
Subtracts one item from another
Income = 1000;
Expense = 750;
Profit = Income - Expense;
*
Multiplies two items
Width = 50;
Length = 20;
Area = Width * Length;
/
Divides one item by another
Persons = 50;
Cost = 200;
CostPerPerson = Cost / Persons;
%
Calculates the remainder after
dividing one value by another
TotalEggs = 64;
CartonSize = 12;
EggsLeft = TotalEggs % CartonSize;
The arithmetic operators shown in Figure 11-13 are also known as binary operators
because they work with two operands in an expression. JavaScript also supports unary
operators , which work on only one operand. Unary operators can make code more
compact and efficient. One of the unary operators is the increment operator , which
increases the value of the operand by 1. The increment operator is indicated by the ++
symbol. For example, the following two expressions both increase the value of the x vari-
able by 1; the first uses the binary operator indicated by the + symbol, and the second
uses the increment operator indicated by the ++ symbol:
x = x + 1;
x++;
 
Search WWH ::




Custom Search