In JavaScript Arrays the first slot is always item 0. ‘zero-indexed’ simply means that counting starts at 0 and not 1. We don’t want to select a non-existent slot 12, we want to end up back at slot 5, with the value AD70CC. So, say for example, we take the scenario given in the first paragraph, we are at slot 2 (in JS that would be the third value as JS is zero-indexed), which is the value 31D1B3 and we try and skip forward 10 slots. We are going to make a div change colour from one colour value to another by taking the existing slot number and adding any number to it. Let’s look at an array of colour values: var colours = OK, so how do use this to solve our looping around problem? Looping around an array with modulos/remainder operator Here again in JavaScript: var remainsOfThirteenByFour = 13 % 4 console.log(remainsOfThirteenByFour) // 1 We can get 3 whole lots of 4 out of 13 which takes us to 12 so we would expect the remains to be 1. What about the remains of dividing 13 by 4? Let’s do another example just to be clear what’s going on. Let’s look at this in JavaScript: var remainsOfEightByThree = 8 % 3 console.log(remainsOfEightByThree) // 2 In English we might say that the remains of dividing 8 by 3 is 2 as we can get two lots of 3 out of 8 giving us 6 and there are then 2 remaining. This operator is used to get the remainder after a division. The key to solving this problem is the Modulo operator, also known as the Remainder operator and expressed in JavaScript with the % symbol.
This is a scenario I’ve come across a few times in the last year or so and as I keep having to remember how to solve the problem I’m writing it out here for developer posterity. This is standard behaviour for carousels and the like. To further exemplify, if you have an array of 8 items, and you are currently on item 2 and you skip along 10, we want to end up back at slot 4 and not a non-existent slot 12. However, you want to loop around them infinitely. They might be colours, pieces of text, DOM nodes, whatever.
Difference between var and let in JavaScript.How to calculate the number of days between two dates in javascript?.ISRO CS Syllabus for Scientist/Engineer Exam.ISRO CS Original Papers and Official Keys.GATE CS Original Papers and Official Keys.