The remainder operator (%) returns what remains after division. It is useful for cycling through items, wrapping animation values, and keeping an index inside a fixed range—but JavaScript’s result can surprise you when the dividend is negative. section 2.5 section 2.5.1
For a five-item cycle, mathematical modulo behaves like movement around a circle:
- 5 mod 5 = 0: completing one full cycle returns to item 0. section 2.5.1
- 6 mod 5 = 1: moving six positions lands on item 1. section 2.5.1
- -1 mod 5 = 4: moving backward once lands on the final item. section 2.5.1
Wrapping a carousel index safely
JavaScript gives the remainder the same sign as the dividend, so -1 % items.length is -1 rather than the final valid index. Normalize the result before indexing: function mod(dividend, divisor) { return ((dividend % divisor) + divisor) % divisor; } A back-button update can then use index = ((index - 1 + items.length) % items.length); section 2.8


