Main Page

Postfix increment/decrement

var iNum = 10;
alert(iNum); //outputs “9”
alert(--iNum); //outputs “8”
alert(iNum); //outputs “8”
The second line decrements
, and the third line displays the result
). The fourth line displays
num once again, but this time the prefix decrement is applied in the same statement, which results in
the number
being displayed. To prove that all decrements are complete, the fifth line once again
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,
is equal to
because the expression evaluates to 1 + 21. The variable
is also equal to
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
a variable:
var iNum = 10;
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;
The second line of code decreases the value of
to 9.
Unlike the prefix operators, postfix operators increment or decrement
the containing expression is
evaluated. Consider the following example:
var iNum = 10;
alert(iNum); //outputs “9”
alert(iNum--); //outputs “9”
alert(iNum); //outputs “8”
Just as in the prefix example, the second line decrements
, 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
. When the fifth line is executed, the alert displays
, because the postfix
decrement was executed after line 4 but before line 5.
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 35

JavaScript EditorFree JavaScript Editor     Ajax Editor