"Prev" / "Next" buttons for a circular list
I recommend splitting up the work into one function that is pure and another one that has side-effects.



const resultBox = document.getElementById('result')
const messages = ["cat", "dog", "fish"];
const length = messages.length;

const getNextIdx = (idx = 0, length, direction) =&gt; {
   switch (direction) {
     case 'next': return (idx + 1) % length;
     case 'prev': return (idx == 0) &amp;&amp; length - 1 || idx - 1;
     default:     return idx;
   }
}

let idx; // idx is undefined, so getNextIdx will take 0 as default
const getNewIndexAndRender = (direction) =&gt; {
     idx = getNextIdx(idx, length, direction);
     result.innerHTML = messages[idx]
}

getNewIndexAndRender();
&lt;p id="result"&gt;&lt;/p&gt;
&lt;button onclick="getNewIndexAndRender('prev')"&gt;prev&lt;/button&gt;
&lt;button onclick="getNewIndexAndRender('next')"&gt;next&lt;/button&gt;




Note: getNextIdx is a pure function, which will never modify any value, it takes the arguments it needs and returns a new value, we pass into it the currentIdx, the lengthOfTheArray and an action which lets the function decide, what to do.