Why is there a big diffrence in using for loop with and without constraints.
With condition
for(var i = 3; i >= 0; i--) { console.log(i); }
outputs
3
2
1
0
Without condition
for(var i = 3; i--;) { console.log(i); }
outputs
2
1
0
Why does the one without condition skip the first iteration and also stop at 0.
If you use no condition but add one instead of subtract it will result in an infinite loop
2
Answers
The second one does have a condition:
i--
. The modification toi
in the condition is a side effect.The condition runs before the log statement (instead of after it) so it doesn’t log
3
becausei
changed too soon.0
is a false value so wheni--
evaluates as0
the condition no longer matches.In your case, the final-expression is not used.
The condition is
i--
and it will stop when this is falsy, which means wheni-- = 0
And the condition is executed every time before each itteration. Thus skipping 3.