Why does CoffeeScript use %% for modulo instead of the standard javascript operator %

coffeescript, javascript, modulo, operators

Solution

I did find the answer in another StackOverflow question and answer JavaScript % (modulo) gives a negative result for negative numbers and I wanted to share it for people who like me only looked for a "CoffeeScript" related explanations and thus have a hard time finding the correct answer.

The reason for using `a %% b` which compiles to `(a % b + b) % b` is that for negative number, like `-5 % 3`, JavaScript will produce a negative number `-5 % 3 = -2` while the correct mathematical answer should be `-5 % 3 = 1`.

The accepted answer refers to an article on the JavaScript modulo bug which explains it well.

Problem

In the CoffeeScript documentation on operators it says that you can use `%%` for true mathematical modulo, but there is no explanation as to why this is different from the "modulo operator" `%` in JavaScript. Further down it says that `a %% b` in CoffeeScript is equivalent to writing `(a % b + b) % b` in JavaScript but this seem to produce the same results for most simple cases.

Original source

Related problems