Categories
JavaScript Answers

How to get the previous and next elements of an array loop in JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *