It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:
10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.
Apparently it is not the same as the modulo operator entirely.
Answer from MarioDS on Stack OverflowVideos
The problem with % is that it is a remainder operator with truncated division, not a modulo one with floored division. When the divisor (i-1) becomes negative, so does the result. You can use
if (--i < 0) i = stuff.length - 1;
or
i = (i + stuff.length - 1) % stuff.length;
instead (which only work for input values of i in the expected range, though)
If you want next() to increment i between 0 and 2 and prev() to decrement between 2 and 0 you can use the following:
next() {
this.props.dispatch(increaseCounter());
i = Math.min(i + 1, stuff.length - 1);
}
prev() {
this.props.dispatch(decreaseCounter());
i = Math.max(i - 1, 0);
}
Since there is (potentially) a larger number of items in the li array, this prevents i from being outside the bounds of the colors array, since i % colorsCount can never be over colorsCount.
For example, if we had 10 elements in li, and 5 colors, i % colorsCount would be:
i i % colorsCount Color
-------------------------------
0 0 salmon
1 1 teal
2 2 orange
3 3 grey
4 4 blue
5 0 salmon
6 1 teal
7 2 orange
8 3 grey
9 4 blue
More Information on Modulo Operations.
i % colorsCount will set the bound of the index to be between 0 and colorsCount-1, thus ensuring you never index past the end of the array.
Since mod is the remainder, the remainder can never be greater than the divisor (which in this case, is the length of the array).