3 ms·
You were right - Javascript lacks a modulo operator. Javascript does have a `%` operator, and in many languages that performs the modulo operation ... but in JS
by smcl 6y ago
You were right - Javascript lacks a modulo operator. Javascript does have a `%` operator, and in many languages that performs the modulo operation ... but in JS it actually calculates the remainder. This is confusing because in some situations remainder and modulo look similar, but they're not. So if we compare JS and Python (where `%` means "modulo") ...
$ python3
Python 3.7.3 (default, Jul 25 2020, 13:03:44)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 10 % 3
1
>>> 10 % -3
-2
>>>
$ node
> 10 % 3
1
> 10 % -3
1
In the case we're talking about - is_odd - I don't think it matters, but there is a difference and it could cause some surprises if you're not prepared.
edit: I called this operation "remainder" ... but you don't exactly say "10 remainder 3" for this operation. I don't know what to call it, "divide-by-and-return-absolute-of-whats-left" is not very catchy
- TimWolla 6y agoAccording to https://en.wikipedia.org/wiki/Modulo_operation#In_programming_languages https://en.wikipedia.org/wiki/Modulo_operation#In_programmin...: - JavaScript is consistent with Java, PHP. - Older C may behave as either Python or JavaScript. - Modern C behaves like JavaScript. So basically Python is the outlier here.
- 3pt14159 6y agoOutlier is a bit of a strong word. Ruby and many others[0] implement it the same way. Personally, I think the way Ruby does it is the most intuitive. The % operator is a modulo, and there is a separate method for remainder. Even though I prefer this way, I'm dismayed that there are multiple ways of doing it. Like so many things created by humanity, we just can't ever seem to take one definition and stick to it. [0] https://en.wikipedia.org/wiki/Modulo_operation#In_programming_languages https://en.wikipedia.org/wiki/Modulo_operation#In_programmin...