Stumbled on a Javascript Bug



This is rare. While writing code, I stumbled on a bug in the language.

In my application, I’m using the mod operator (%) and I have used it for decades successfully (although not only in JavaScript).

So the thing I’m working on has a circular array so I need to move the index pointer from the end to the beginning when it rolls over. I inserted the mod but started seeing a value of -1 around the beginning/end of the array. More specifically, I was moving backwards in the array (10,9,8) and when I got to 0 and subtracted 1 from the “current” index, I was expecting the top of the array as the next value. Instead I was getting -1. Wha?

I do not remember ever having to use the mod operator against negative numbers and thus had some uncertainty. I typically have used mod for continuously incrementing values like line counters, page numbers etc. I jumped to Google drive spreadsheet to sanity check myself and it was calculating correctly… that covered Javascripts’ tracks for a while and made me think it was my logic. After more troubleshooting, I wrote the smoking gun validation code:

alert((-1) % 16);

(I added the internal parens just in case there was a weird precedence rule in Javascript.)

So a quick Google indicated my problem. there is a bug in the mod operator in Javascript with negative numbers. Ouch.



There are elegant solutions mathematically, but I chose to use an “if” statement and manually set the value in the special case.

I believe that simple and obvious code is better than elegant and cryptic. It’s about programmer productivity over software efficiency … a core belief of mine. (although in this case, the “if” may be faster as well)