Typically in contemporary JavaScript we iterate over arrays with Array.map()
, .reduce()
, .forEach()
, etc. These techniques assume we want to get through the entire array from start to finish all in one go. However, what if you have a slideshow that displays an array of images one at a time, and upon reaching the last image, you want to start over at the first?
For this sort of behavior, we can leverage the Remainder operator to automatically loop around the array to infinity. The for
loop below makes it a little easier to visualize how this works.
const numRuns = 11;
const arr = ['a', 'b', 'c', 'd', 'e'];
for (i = 0; i < numRuns; i++) {
const m = i % arr.length;
console.log(`${i} % ${arr.length} = ${m}, arr[${m}] = ${arr[m]}`);
}
0 % 5 = 0, arr[0] = a
1 % 5 = 1, arr[1] = b
2 % 5 = 2, arr[2] = c
3 % 5 = 3, arr[3] = d
4 % 5 = 4, arr[4] = e
5 % 5 = 0, arr[0] = a
6 % 5 = 1, arr[1] = b
7 % 5 = 2, arr[2] = c
8 % 5 = 3, arr[3] = d
9 % 5 = 4, arr[4] = e
10 % 5 = 0, arr[0] = a
Top comments (0)