How come this if statement doesn't work (codepen included)

A Pen by Trenton (codepen.io)

the function at the very bottom of my JS file called “checkForEnd” is not working as intended and I’m not sure why?

basically, all I want it to do is check to see if there are any more cards left in the array and if it’s at the last card then set the array Index back to 0.

what is wrong with my code?

Your incrementArrayIndex increments the index before calling renderCards, so since there are 4 cards in the array and when the 4th card is showing, that means arrayIndex is already 3. If you click Next again, you increment arrayIndex to 4 but since there are only 4 elements in the array, the 4 tries to reference a 5th element in your renderCards function and errors out. The code in checkForEnd function never gets executed because of the error.

Also, if you hit the Before button, enough times, arrayIndex will become negative, so your checkForEnd would never have the condition of arrayIndex being equal to cardsArray.length.

JavaScript arrays are zero-indexed, so you will need to rethink your logic a bit.

Thank you for the response, I’m trying to work on fixing this.

I tried to do this just to see if it would work and the arrayIndex matches up and hits 3 but nothing happens.

function incrementArrayIndex() {
    ArrayIndex++
    renderCards()
    console.log(ArrayIndex)
}
function decrementArrayIndex() {
    ArrayIndex--
    renderCards()
    console.log(ArrayIndex)
}

function checkForEnd() {
    if (ArrayIndex === 3) {
        ArrayIndex = 0
        renderCards()
    }
}

I’m trying to prepare myself for a project I want to do but I need to understand this better before I do so.

Post your full latest code. I do not see where you are calling checkForEnd function.