Iterate Over An Array With The Modulo Operator
2 min read

The Problem

We want to iterate over an array, for this particlar example, let’s say it has 10 values. When we pass the tenth object, we want to start over from object number one.

If we would use a normal for loop, the array would be out of bounds quite soon if we didn’t manually reset the index.

problem

The solution

We can use the modulo operator to fix this problem without having to use to much logic. By simply adding it we can define a “max” value, allowing or the value to start over from 0 instead of continuing counting on for all eternity.

let nextIndex = (currentIndex + 1) % arrayLength;

This would always keep the nextIndex variable (in this case), to never pass 10.

modulo solution

This example works if you want to iterate upwards, always adding a number. There is a slight difference if you want to go the other way, with subtraction.

const arrayLength = 10;
let currentIndex = 10;

let nextIndex = (currentIndex - 1 + arrayLength) % arrayLength;