Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can somebody explain why -1 is used in javascript

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading