Power of Backward Loops

Loops aka cycles (while, for, do until, etc) are common in programming. Actually they are a language level implementation of the iterator pattern.

Those who learned programming in the college/university, remember lots of tasks for sorting an array or traverse a double-linked list in both directions. But in practice, very few people apply the backward loops.

There are a number of tasks where the reverse iteration automatically solves a bunch of problems, for example:

If you need to release all elements of array/collection/list, it is much easier to start from the end and delete the last element each time, rather then go from the beginning, save the length of the container, make the reference for every deleting object, and so on.

Compare this:

var len = someCollection.length();
for (i = 0, i < len, i++) {
    var element = someCollection[i];
    someCollection.delete(i);
    delete element;
}

with that:

var i = someCollection.length();
while (i--) {
    delete someCollection[i];
}

So the backward loop is not only for students, the backward traverse rules in many cases 🙂

Author: BgRnD Official

Official representative of BgRnd Team on this website

Leave a Reply