↑
Main Page
Postfix increment/decrement
var iNum = 10;
--iNum;
alert(iNum); //outputs “9”
alert(--iNum); //outputs “8”
alert(iNum); //outputs “8”
The second line decrements
num
, and the third line displays the result
(“9”
). The fourth line displays
num once again, but this time the prefix decrement is applied in the same statement, which results in
the number
“8”
being displayed. To prove that all decrements are complete, the fifth line once again
outputs
“8”
.
The prefix increment and decrement are equal in terms of order of precedence when evaluating a mathe-
matical expression and, therefore, are evaluated left to right. For instance:
var iNum1 = 2;
var iNum2 = 20;
var iNum3 = --iNum1 + ++iNum2; //equals 22
var iNum4 = iNum1 + iNum2; //equals 22
In the previous code,
iNum3
is equal to
22
because the expression evaluates to 1 + 21. The variable
iNum4
is also equal to
22
and also adds 1 + 21.
Postfix increment/decrement
Two operators, also taken directly from C (and Java), are the postfix increment and postfix decrement.
They also add one to a number value, as indicated by the two plus signs (++) placed
after
a variable:
var iNum = 10;
iNum++
As you might expect, postfix decrement subtracts one from a value and is indicated by two minus signs
(– –) placed after the variable:
var iNum = 10;
iNum--;
The second line of code decreases the value of
iNum
to 9.
Unlike the prefix operators, postfix operators increment or decrement
after
the containing expression is
evaluated. Consider the following example:
var iNum = 10;
iNum--;
alert(iNum); //outputs “9”
alert(iNum--); //outputs “9”
alert(iNum); //outputs “8”
Just as in the prefix example, the second line decrements
iNum
, and the third line displays the result (9).
The fourth line displays num once again, but this time the postfix decrement is applied in the same state-
ment. However, because the decrement doesn’t happen until after the expression is evaluated, this alert
also displays the number
9
. When the fifth line is executed, the alert displays
8
, because the postfix
decrement was executed after line 4 but before line 5.
35
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 35
Free JavaScript Editor
Ajax Editor
©
→ R7