+ 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.
3 odpowiedzi
+ 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.
0
What's the difference post decrement and pre decrement
0
Eddy Ricchy,
Pre: decrement the value and then use it;
Post: use the value and then decrement it.