8

Possible Duplicate:
++someVariable Vs. someVariable++ in Javascript

I know you can add one to a variable simply by doing i++ (assuming i is your variable). This can best be seen when iterating through an array or using it in a "for" statement. After finding some code to use online, I noticed that the for statement used ++i (as apposed to i++).

I was wondering if there was any significant difference or if the two are even handled any differently.

Community
  • 1
  • 1
Freesnöw
  • 30,619
  • 30
  • 89
  • 138
  • Answer here: [http://stackoverflow.com/questions/3469885/somevariable-vs-somevariable-in-javascript](http://stackoverflow.com/questions/3469885/somevariable-vs-somevariable-in-javascript) – pixelbobby May 16 '11 at 16:56

6 Answers6

29

Yes there is a big difference.

var i = 0;

var c = i++; //c = 0, i = 1
    c = ++i; //c = 2, i = 2
    //to make things more confusing:
    c = ++c + c++; //c = 6
    //but:
    c = c++ + c++; //c = 13

And here is a fiddle to put it all together: http://jsfiddle.net/maniator/ZcKSF/

Naftali
  • 144,921
  • 39
  • 244
  • 303
4

The value of ++i is i + 1 and the value of i++ is just i. After either has evaluated, i is i + 1. It's a difference in timing, which is why they're often called 'pre-increment' and 'post-increment'. In a for loop, it rarely matters, though.

Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151
3

People like Douglas Crockford advise not to use that way of incrementing, amongst other reasons because of what Rafe Kettler described. No matter how experienced you are, sometimes ++i/i++ will suprise you. The alternative is to simply add 1 to i using i += 1, readable, understandable and unambiguous.

KooiInc
  • 119,216
  • 31
  • 141
  • 177
2

have a look at this link : http://www.w3schools.com/js/js_operators.asp it's post increment versus pre increment. They both end up incrementing the value but one returns the value BEFORE incrementing (++y) and the other one returns the value AFTER (y++). However, it doesn't make any difference when using it in a for loop --

for( var i = 0; i < 100; i++ ) { ... }

is the same as

for( var i = 0; i < 100; ++i ) { ... }
Liv
  • 6,006
  • 1
  • 22
  • 29
2
a=1;
b=1;
c=++a;//the value of a is incremented first and then assigned to c
d=b++;//the value of b is assigned to d first then incremented

now if you print a,b,c,d..the output will be:

2 2 2 1

painotpi
  • 6,894
  • 1
  • 37
  • 70
1

++i is called pre-increment and i++ is called post-increment. The difference is when the variable is incremented. Pre-incrementing a variable usually adds 1 and then uses that value, while post-incrementation uses the variable and then increments.

SquidScareMe
  • 3,108
  • 2
  • 24
  • 37