I have been conducting a few tests in Javascript, I will show them (pasted from console):
-1 % 4
-1
-4 % 4
-0
-8 % 4
-0
-6 % 4
-2
-6 % -4
-2
6 % -4
2
-1 % 4 is truly -1, however, I do not really understand why is Javascript not yielding 3, which is equally correct, but more canonic.
What is -0? I know -4 / 4 = -1, which is an integer, but I am not sure what -0 is.
I am puzzled about Javascript's calculation of modulo.
My tests were motivated by a slightly unpleasant surprise that I have been working on a gallery and I have an index for the active picture. There are two buttons, for next and previous buttons. The next image of the last image is the first image and the previous image of the first image is the last image. I have been changing the index as:
currentImageIndex = (currentImageIndex + 1) % images.length;
when the user clicked on the next button. When the user clicked on the previous button, I have been trying with the following code:
currentImageIndex = (currentImageIndex - 1) % images.length;
I was surprised to see that the latter did not work well, as the previous image was not shown and an error was thrown as an invalid index was used in the array indexed by currentImageIndex. I have console.log-ed the value and have seen that it is -1! Ok, I have worked around the problem with:
currentImageIndex = (currentImageIndex + images.length - 1) % images.length
and it was not too painful, but still, I did not understand the logic behind the result of the calculation. So, is there somebody, who kows how Javascript's modulo calculation works, as I am really puzzled and I see -0 as a result of -4 % 4 to be the joke of the month.