Javascript Reference
Categories: Operators

javascript Operators -

@March 15, 2008, 1:22 a.m.
Firefox/Netscape/NN 2 IE 3 ECMA 1  

  

The decrement operator (a unary operator) subtracts 1 from the current value of a variable expression. You can place the operator in front of or behind the variable for a different effect. When the operator is in front of the variable, the variable is decremented before it is evaluated in the current statement. For example, in the following sequence:

var a, b;
a = 5;
b = --a;
 

one is subtracted from a before being assigned to b. Therefore, both b and a are 4 when these statements finish running. In contrast, in the following sequence:

var a, b;
a = 5;
b = a--;
 

the subtraction occurs after a is assigned to b. When the statements complete, b is 5 and a is 4.

 

This behavior impacts the way for-loop-counting variables are defined and used. Typically, a loop counter that counts backwards from a maximum value decrements the counter after the statements in the loop have run. Thus most loop counters place the operator after the counter variable:

for (var i = 10; i>=0; i--) {...} 
 
Example
 
--n
n--

Powered by Linode.