0
for (var i=0;i<5;++i){
alert(i);

}


for (var i=0;i<5;i++){
alert(i);

}

These two constructs return the same result: 0,1,2,3,4. Why? What are the differences between them? Does it matter what increment i use in for loop?

DrStrangeLove
  • 11,227
  • 16
  • 59
  • 72

5 Answers5

2

If you put ++ in front of the variable you increment the value before returning it (in that statement), if you put it behind you return the value, then increment it afterwards. Since you are doing nothing with the value in the statement the result after said statement is the same.

Consider this:

var i = 0;
var a = ++i; // a is 1
var b = i++; // b is also 1, i is now 2.
Vala
  • 5,628
  • 1
  • 29
  • 55
  • It doesn't (unless you place it inside the conditional) - like for (int i = 0, y++ < 3; i++) - or something like that. – Matt Razza Oct 11 '11 at 15:15
  • If you look at the way the for loop is written it has 3 statements: for (initial statement; conditional; between-loops). Your i++ is alone in the between-loops bit. Since that statement is entirely self-contained there the increment will always be done before you get to any other code. – Vala Oct 11 '11 at 15:32
1

The former is a pre-increment, the latter a post-increment.

The difference is nothing your example as you're not assigning the result to anything, but show themselves quite alot when assigning the result to another variable.

var i = 0;
alert(i); // alerts "0"

var j = i++;
alert(j); // alerts "0" but i = 1

var k = ++i; 
alert(k); // alerts "2" and i = 2

Live example: http://jsfiddle.net/ggUGX/

Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

for a loop you dont see any difference, but the ++i increments and then returns the value wheras i++ returns a value and then increments. If you have code like

var a = myarray[++i]

and

var a = mayarray[i++];

they will return differnet values

0

These two code blocks should have the same output. The difference between i++ and ++i is the order in which the variable i is incremented and is only important when using the value of i at the same time.

For instance, ++i and i++ do effectively the same thing unless you're using it like so:

y = i++;

or

y = ++i;

In the first example i is incremented AFTER y is set to its value (so if i = 0, y = 0, then i = 1). In the second example i is incremented BEFORE y is set to its value (so if i = 0, i = 1, y = 1).

Because you do not use i++ in a similar fashion in a for statement, it has no effective difference.

Matt Razza
  • 3,524
  • 2
  • 25
  • 29
0

i++ or ++i in the for loop executes as a different statements. So, putting i++ or ++i in for loop doesn't make any difference.

Sapan Diwakar
  • 10,480
  • 6
  • 33
  • 43