What does while(i--) mean in javascript?
The number 0
is considered falsey in JavaScript, so the while loop will run until it hits 0. You would have to be sure that i is positive to start off with, otherwise you've got an infinite loop.
var i = bullets.length;
while (i--) {
...do stuff...
}
is essentially equivalent to:
var i = bullets.length;
while (true) {
if (i === 0) {
i = i - 1;
break;
}
i = i - 1;
...do stuff...
}
This style of looping tends to be used where performance is super important, as it's slightly faster than iterating indices from 0
to length-1
, and is relatively straight-forward to implement.
Generally speaking, you shouldn't use it unless you're improving a known bottleneck and have verified that it improves performance in a significant way.
It will first check i
value (if not zero), then enter loop after having decremented i
.
So, if i
= 10, loop will be executed with i
= 9, i
= 8, .., i
= 0 and then exit
(because in last i--
check, i
will be already zero from previous loop run)