Create Infinite Carousel Loop in JavaScript

- 2 minutes read

The following JavaScript function turns an array into an object that can be treated like an infinite loop:

const createCarousel = (array) => {
    array.index = 0;
    array.current = function() {
        this.index = this.index % array.len;
        return array[this.index];
    };
    array.next = function() {
        this.index++;
        return this.current();
    };
    array.previous = function() {
        this.index += array.len - 1;
        return this.current();
    };
    array.reset = function() {
        this.index = 0;
        return array[0];
    };
};

Passing an array to the above function adds four custom methods to the array: current(), next(), previous(), and reset().

An internal counter is also added to the array, which keeps track of the current position in the loop.

Here is some example usage:

const array = [1, 2, 3];

createCarousel(array);

array.current(); // Returns "1"

array.next(); // Returns "2"

array.next(); // Returns "3"

array.previous(); // Returns "2"

array.reset(); // Returns "1"

It’s important to note that modifying the array length without immediately resetting the counter can cause unwanted behavior.

Link to this section Conclusion

And that’s one way you can go about turning an array into an infinite loop in JavaScript!

This comes in handy for things like image carousels, ticker tapes, and news feeds.