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; i
with 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?
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++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With