v7vliq
Last Updated: February 25, 2016
·
1.572K
· stathisg
Twitter avatar

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.

Say Thanks
Respond

1 Response
Add your response

6622
0e2e822d32a7ab3d7f0b7098d03b1d16

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 ·