Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 441
Christian Avatar asked Mar 12 '23 13:03

Christian


1 Answers

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++;
}
like image 161
Tuvia Avatar answered Mar 16 '23 02:03

Tuvia