I am watching a javascript tutorial to create testimonial slider.in this javascript project i didn’t understand why they use "slides.length-1".Why cant we give only slide.length only.why -1 should be included in the code can anybody explain?
const next = document.querySelector('.next');
const prev = document.querySelector('.prev');
const slides = document.querySelectorAll('.slide');
let index = 0;
display(index);
function display (index) {
slides.forEach((slide) => {
slide.style.display = 'none';
});
slides[index].style.display = 'flex';
}
function nextSlide () {
index++;
if (index > slides.length - 1) {
index = 0;
}
display(index);
}
function prevSlide () {
index--;
if (index < 0) {
index = slides.length - 1;
}
display(index);
}
next.addEventListener('click', nextSlide);
prev.addEventListener('click', prevSlide);
>Solution :
This is all because we count indexes from 0
Imagine having an array of length 5. This means that array has 5 elements.
But their indexes are: 0, 1, 2, 3, 4 (five elements in total).
That’s why when you want to access last element of any array you use:
myArray[myArray.length - 1]
which is literally myArray[5 - 1] so myArray[4]. And as I mentioned, indexes in array of length 5 are: 0, 1, 2, 3 and last but not least: 4