Christian
Christian

Reputation: 6430

Why have for-loops with pre-increment the same behaviour as those with post-increment?

It's probably fair to say everyone learns writing for-loops using post-increment:

for(var i = 0; i < 10; i++) {
  console.log(i); // 0..9
}

When I swap the post-increment out for a pre-increment, I'd expect the following:

for(var i = 0; i < 10; ++i) {
  console.log(i); // 1..10
}

My reasoning: i is initialised to 0; the loop's body will be executed while i is less than 10; i is incremented to 1 and the loop's body is entered; iwith value 1 is printed to consele; the loop's condition is evaluated again; etc.

Yet the output is (at least for JavaScript in Chrome) the same as for a post-increment: 0..9. Why is that? Is the increment executed after the body is run?

Upvotes: 5

Views: 1292

Answers (3)

aaronofleonard
aaronofleonard

Reputation: 2576

Is the increment executed after the body is run? Yes.

See those semicolons? They mean that they are entirely different expressions.

Take this small example:

var i = 0;
if (i<5)
    i++;
console.log(i);

and

var i = 0;
if (i<5)
    ++i;
console.log(i);

(These examples are not replicating the functionality of a loop.) You see, you'll get the same answer for both, because just like a for loop, they are entirely separate expressions.

Now, if you had:

var i = 0;
i += i++;
console.log(i);

and

var i=0;
i+= ++i;
console.log(i);

Ahh, since the operators are being used in the same expression, then the one we use matters!

That is basically what is happening. Since they are different expressions, imagine them being run on different lines.

Upvotes: -1

djechlin
djechlin

Reputation: 60768

In the latter example the sequence of operations is

var i = 0; // obviously
if (i < 10) /* proceed */
console.log(i); 
++i;

The "++" doesn't say "jump the queue and do the operations in an entirely different order," as you seem to suspect.

Upvotes: -1

Tuvia
Tuvia

Reputation: 869

The last part of the for loop only happens at the end of each loop.

So ++i and i++ do basically the same thing in that case.


Order of operations:

var i = 0;

while (i < 10) {
   // do stuff
   console.log(i);
   // increment i in your own way
   ++i; // or i++;
}

Upvotes: 9

Related Questions