Javascript Reference
Categories: Operators

javascript Operators ++

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

  

The increment operator (a unary operator) adds 1 to 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 incremented before it is evaluated in the current statement. For example, in the following sequence:

var a, b;
a = 5;
b = ++a;
 

1 is added to a before being assigned to b. Therefore, both b and a are 6 when these statements finish running. In contrast, in the following sequence:

var a, b;
a = 5;
b = a++;
 

the addition occurs after a is assigned to b. When these statements complete, b is 5 and a is 6.

 

This behavior impacts the way for-loop-counting variables are defined and used. Typically, a loop counter that counts upward from a minimum value increments 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.