+ 1

Zero Validates?

I am not sure why the code below prints 0. var i = 5; while(i--) document.write(i + '<br>'); //outputs 4 3 2 1 0 On the 5th iteration i = 0. I thought 0 == FALSE and the while loop will not validate. But this doesn't seem to be the case here. What am I getting wrong? I am a beginner in JavaScript.

19th Oct 2020, 9:16 AM
Logos
Logos - avatar
3 Answers
+ 4
You should edit your code: var i = 5; while(--i) document.write(i + '<br>'); //outputs 4 3 2 1 // that's beacuse of post-decrement (i--). You should use pre-decrement (--i), because in post-decrement case variable i is being changed after the iteration.
19th Oct 2020, 9:22 AM
Artem đŸ‡ș🇩
Artem đŸ‡ș🇩 - avatar
0
What's the difference post decrement and pre decrement
19th Oct 2020, 9:08 PM
Logos
Logos - avatar
0
Eddy Ricchy, Pre: decrement the value and then use it; Post: use the value and then decrement it.
20th Oct 2020, 3:25 AM
Artem đŸ‡ș🇩
Artem đŸ‡ș🇩 - avatar