How to optimize js code?

Hello. Please help me to optimize the js code for the slider:

/* The index of the slide by default */
var slideIndex = 1;
showSlides(slideIndex);

/* Function increases the index by 1, shows the following slide*/
plusSlide function() {
 showSlides(slideIndex += 1);
}

/* Function umenshaet index 1, shows previous slide*/
minusSlide function() {
 showSlides(slideIndex -= 1); 
}

/* Sets the current slide */
function currentSlide(n) {
 showSlides(slideIndex = n);
}

/* The main function of the slider */
showSlides function(n) {
 var i;
 var slides = document.getElementsByClassName("item");
 var dots = document.getElementsByClassName("slider-dots_item");
 if (n > slides.length) {
 slideIndex = 1
}
 if (n < 1) {
 slideIndex = slides.length
}
 for (i = 0; i < slides.length; i++) {
 slides[i].style.display = "none";
}
 for (i = 0; i < dots.length; i++) {
 dots[i].className = dots[i].className.replace(" active", "");
}
 slides[slideIndex - 1].style.display = "block";
 dots[slideIndex - 1].className += "active";
}
March 19th 20 at 08:51
3 answers
March 19th 20 at 08:53
In the shown code, a lot of things could be improved. But do not understand your goals and the scope of the problem.
Offhand:
0. Why not use some kind of library? Not necessarily a lot like Slick, there are options easy.
1. To think what would happen if the sliders on the page will be more than one?
2. To write jQuery functions like addClass/removeClass (unless you want to use the classList). To work with "active" (with a space) is dangerous.
3. To make the class names in the constants. And use BEM ("item" can meet anywhere).
4. Can vary the number of slides and points? Judging by the code - no, but then why two cycles?
5. Assign display: "block" is also dangerous because there could theoretically be something different (flex for example).
6. The name of the function currentSlide bad - do not understand what it does. A getter or setter?
March 19th 20 at 08:55
well you can check that the index is not beyond the bounds of the array, and in showSlides to send just 1 or -1, type to the next slide or previous ... and Yes, it works well and reads well

/* Sets the current slide */
function currentSlide() {
showSlides();
}

/* Function increases the index by 1, shows the following slide*/
plusSlide function() {
showSlides(+1);
}

/* Function umenshaet index 1, shows previous slide*/
minusSlide function() {
 showSlides(-1); 
}

/* The main function of the slider */
function showSlides(n = 0) {
 // set the next slide so
 slideIndex = (slideIndex + n) % slides.length < 0 
 ? slides.length - 1 
 : (slideIndex + n) % slides.length


 ....
March 19th 20 at 08:57
What do you optimize? The same task is not clear on the slider.
If you need to make a second slider on the page that is not working code.

Find more questions by tags Web DevelopmentJavaScript