A small iteration tip

Just a quick note: I recently started adding a few tips to my Coderwall profile, but I decided to begin publishing them here as well, in their own coding tips category.

Here is the first one:

When coding in JavaScript, it’s often needed to constantly iterate through the contents of an array, using a function called from a setInterval method (example).

Until now, I was doing something like the following:

arrayOfSth = ['one', 'two', 'three'];
count = 0;

function onLoad() {
    setInterval(iterate, 1000);
}

function iterate() {
    alert(arrayOfSth[count]);

    if(count < arrayOfSth.length - 1) {
        count++;
    } else {
        count = 0;
    }
}

But, instead of the whole check at the end of the iterate function to increment (or reset) the count variable, I’m now doing the following:

count = (count + 1) % arrayOfSth.length;

It has the exact same effect, but it’s fancier and cleaner.

If you find this useful and you have a Coderwall account, please feel free to upvote it.

Photo by Andre Wagner