HTML and CSS Reference
In-Depth Information
A similar operator is the decrement operator , indicated by the -- symbol, which
decreases the operand's value by 1. Thus, the following two expressions have the equiva-
lent impact of reducing the value of the x variable by 1:
x = x - 1;
x--;
Both the increment and decrement operators can be placed either before or after the
operand. The placement impacts the value ultimately assigned by JavaScript. If the
operator is placed before the operand, the increment or decrement happens before the
operand is evaluated and assigned to another variable. If the operator is placed after the
operand, the operand is evaluated and assigned to another variable, and then it is incre-
mented or decremented. For example, if the x variable has an initial value of 5, then the
statement
x = 5
y = x++; // y = 5 and x = 6
assigns a value of 5 to the y variable and then increments the value of the x variable
by 1, changing its value to 6. If you switch the order so that the increment operator
appears before the expression as follows
To avoid misinterpreting
the actions of an incre-
ment or decrement opera-
tor, read the action of the
operator from left to right,
updating the value of the
operand as you go.
x = 5
y = ++x; // y = 6 and x = 6
then JavaScript first increases the value of the x variable by 1 and then assigns that incre-
mented value to the y variable. The end result is that both x and y have a final value of 6.
Another unary operator is the negation operator , which changes the sign of (or
negates) an item's value. Figure 11-14 summarizes the three unary operators.
Figure 11-14
unary operators
Operator
Description
Example
Equivalent To
++
Increases the item's value by 1
x++
x = x + 1
--
Decreases the item's value by 1
x--
x = x - 1
-
Changes the sign of the item's value
-x
x = 0 - x
Using Assignment Operators
JavaScript statements also use operators when assigning values to items. These operators
are called assignment operators . The most common assignment operator is the equal
sign ( = ), which assigns the value of one expression to another. JavaScript also allows
you to combine the act of assigning a value and changing a value within a single opera-
tor. For example, both of the following expressions add the value of the x variable to the
value of the y variable and then store that sum in the x variable:
x = x + y;
x += y;
An assignment operator also can be used with numbers to increase a variable by a spe-
cific amount. Both of the following expressions increase the value of the x variable by 2:
x = x + 2;
x += 2;

Search WWH ::

Custom Search