Reputation: 2728
I have written the following loop:
for (i = 10; i--; i > 5) {
console.log(i);
}
Which outputs this to the console:
9
8
7
6
5
4
3
2
1
0
Can anyone tell me why it's doing this?
I had a look and it seems like it's just a simple matter of having to increment using the third parameter of the for
loop, rather than the second, but I'm fascinated as to the digits logged to the console. Can anyone give me a simple explanation of why it outputs the numbers it does?
Upvotes: 1
Views: 116
Reputation: 30813
The for loop
has this structure:
for (initial condition ; termination condition ; incremental condition)
In your for loop
, the termination and incremental condition are swapped (!):
for (i = 10; i--; i > 5)
That is:
initial condition: i = 10
termination condition: i-- !!!
incremental condition: i > 5 ??? Does not do incremental
Then, as long as the termination condition returns true
(that is, when i > 0
), the loop continues.
And since i
, having an initial value of 10
, will only become 0
after the i--
is executed 10
times, the result returned was:
9 8 7 6 5 4 3 2 1 0
Totaling 10 loops.
Upvotes: 4
Reputation: 8049
The loop did not finish when you expected because Boolean(i--)
is false only if i == 0
; in short, you misplace compare and action in the loop.
Upvotes: 1
Reputation: 3914
Question is now corrected so ignore: Firstly, you are wrong - it does not produce the output you indicated :). Instead it produces the following:
for (i = 11; i--; i > 5) {console.log(i);}
// 10 9 8 7 6 5 4 3 2 1 0
It starts with 10, not with 9 :).
Secondly, you are not allowed to change the order of statements in the for block. Instead, you must specify them as shown:
for (i = 11; i > 5; i--) { console.log(i); }
// 11 10 9 8 7 6
Third (and most important):
i
; whatever value you want or need.i
.Upvotes: -1