not able to understand the use of the following elements in the given code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

not able to understand the use of the following elements in the given code

what is the use of:- var num=0 in first line of code, num++ in in 4th line, if(num>=images.length) { num=0 } in 5th and 6th line, slider.src[num] in 7th line, num-- in 10th line, if(num<0){ num=image.length-1 in 12th line GIVEN CODE :- var images = [ "http://www.sololearn.com/uploads/slider/1.jpg", "http://www.sololearn.com/uploads/slider/2.jpg", "http://www.sololearn.com/uploads/slider/3.jpg" ]; var num = 0; function next() { var slider = document.getElementById("slider"); num++; if(num >= images.length) { num = 0; } slider.src = images[num]; } function prev() { var slider = document.getElementById("slider"); num--; if(num < 0) { num = images.length-1; } slider.src = images[num]; } REQUEST:- please upvote this question

15th Jul 2020, 5:25 PM
Kumar Sarthak
Kumar Sarthak - avatar
1 Answer
+ 15
var num = 0 initializes a variable, which stores the current index of the image shown in the slider. num++ increments the variable. When you call next() and "num" becomes 4, "num = 0" is executed, which is used to select a URL from the array below the line. slider.src = images[num] images[num] takes an element with an index equal to "num" from the array "images". slider.src = images[num] sets the string to slider.src which represents an image shown on the page. num-- dencrements the variable. When you call prev() and "num" becomes -1, "num = images length - 1" is executed, which is used to select a URL from the array below the line. image.length returns the number of elements in the array. image.length - 1 returns the last index of the array. As you can see "num" can be any value from 0 to 3 (the last index in the array "images").
15th Jul 2020, 5:42 PM
Igor Makarsky
Igor Makarsky - avatar