Reputation: 4479
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?
Upvotes: 4
Views: 607
Reputation: 413737
The third expression in the for
loop header is evaluated after each iteration. Thus:
i
is initialized to 1
i <= 3
, is evaluated (and found to be true
)i++
or ++i
happensExcept for the minor syntax differences, that's exactly what would have happened in a C program in 1976.
Upvotes: 9