I was going through some JavaScript code when a loop structure caught my eye. It wasn’t anything particularly special, rather it iterated in a manner different from what I do. When I need to loop something that isn’t dependent on order, I typically count up, iterating from beginning to end, like so:
do
{
// I feel like I'm going in circles
i++;
} while (i < length)
However, this JavaScript function counted down, looping from end to beginning.
var i = data.length - 1;
if(i >= 0)
{
do
{
// Around and around, we go
}while(i--)
}
Is there any advantage to counting downward or is it just up to developer preference?
I you are removing things from the array, going backwards is better.
Consider you have an array of 10 things, and you end up wanting to remove items at indexes 3 and 4, thru some conditional that is executed during the loop. You are incrementing your counter. When you remove at 3, what happens to the array vis-a-vis the counter? The array length shrinks to 9, what was at index 4 is now at index 3, and you increment the counter to 4. You just skipped something you wanted to delete. If you go backwards, you avoid this issue.
Also, going backwards is faster, because processors can compare the index to 0 faster than they can compare the index to a random number.