To get the previous and next elements of an array loop in JavaScript, we use the modulo operator.
For instance, we write
const len = array.length;
const current = array[i];
const previous = array[(i + len - 1) % len];
const next = array[(i + 1) % len];
to get the current array item with index i
.
We get the previous item’s index with (i + len - 1) % len
.
And we get the next item with index (i + 1) % len
.