Last Updated: September 29, 2021
·
1.828K
· stathisg

A small iteration tip

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.

1 Response
Add your response

Neat trick, but be aware that clever code can introduce bugs if being maintained by someone unfamiliar with your trickery :) I'd be sure to leave a very descriptive comment by that line.

over 1 year ago ·