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.

1

6 Answers 6

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/

Sign up to request clarification or add additional context in comments.

2 Comments

+1 because you show the behavior instead of just describing it as "pre-increment/post-increment".
This will be the answer... in 8 minutes :3
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.

Comments

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.

1 Comment

Nice post :) Thanks for the comment!
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 ) { ... } 

1 Comment

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.