Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does ++i not increment i before for loop?

So the following two functions print out the same exact results.

console.log("i++");
 for (i=1; i<=3; i++) {
  console.log(i); // 1, 2
}
console.log("++i");
for (i=1; i<=3; ++i) {
  console.log(i); // 1, 2
}

This very counter intuitive as I'm specifically asking to post-increment one and per-increment the other. It would be very desirable behavior to increment the value before the run inside the for loop. Is this behavior consistent?, Is this javascript specific or is this the standard behavior across programming languages that use ++i, i++ syntax and for loops?

like image 712
lonewarrior556 Avatar asked Oct 26 '25 07:10

lonewarrior556


1 Answers

The third expression in the for loop header is evaluated after each iteration. Thus:

  1. i is initialized to 1
  2. The loop test expression, i <= 3, is evaluated (and found to be true)
  3. The loop body is executed
  4. i++ or ++i happens

Except for the minor syntax differences, that's exactly what would have happened in a C program in 1976.

like image 155
Pointy Avatar answered Oct 27 '25 22:10

Pointy