Ad

If Statement Confuses Me

- 1 answer

I have this code here for a slider and I don't understand what if statement does.

In my head are 2 options

First, if the current === sliderImages.length - 1 then current === 1, second, if the current === sliderImages.length - 1 then the current === 2 (the length of the array) then take away one.

Here is my (JavaScript) code:

let sliderImages = document.querySelectorAll(".slide"),
  arrowLeft = document.querySelector("#arrow-left"),
  arrowRight = document.querySelector("#arrow-right"),
  current = 0;

// Clear all images
function reset() {
  for (let i = 0; i < sliderImages.length; i++) {
    sliderImages[i].style.display = "none";
  }
}

// Init slider
function startSlide() {
  reset();
  sliderImages[0].style.display = "block";
}

// Show prev
function slideLeft() {
  reset();
  sliderImages[current - 1].style.display = "block";
  current--;
}

// Left arrow click
arrowLeft.addEventListener("click", function() {
  if (current === 0) {
    current = sliderImages.length;
  }
  slideLeft();
});

// Show next
function slideRight() {
  reset();
  sliderImages[current + 1].style.display = "block";
  current++;
}

// Right arrow click
arrowRight.addEventListener("click", function() {
  if (current === sliderImages.length - 1) {
    current = -1;
  }
  slideRight();
});

startSlide();
Ad

Answer

I think your problem comes from thinking about specific numbers on your array. Imagine instead you have an array with n numbers.

if (current === sliderImages.length - 1) {
  current = -1;
}

The sliderImages.length would be n (10 for example, or 20, any number).

Your current variable tells you which image you're currently showing. So if you click the Right Arrow then you want to move one step to the right. But if you're on the last position of the array, the next image, would be the first image. So you do current = -1

In other words: that if is checking whether you're in the last image if so, move back to the first position on the array.

Ad
source: stackoverflow.com
Ad