Modulo Operator %%

Claude Pache claude.pache at gmail.com
Thu Aug 15 06:39:52 UTC 2019



> Le 12 août 2019 à 22:00, Matthew Morgan <mmm211 at zips.uakron.edu> a écrit :
> 
> JS needs a modulo operator. It currently has the remainder operator `%` which works in most cases except for negative values. I believe the the `%%` would work great and be easy to remember. 
> 
> let x = (-13) %% 64;
> is equivalent to  
> let x = ((-13 % 64) + 64) % 64;

Is there a strong advantage of an `%%` operator over a `Math.mod()` function? There is the precedent of the `**` operator implemented as alternative of `Math.pow()` few years ago. It would be interesting to hear the feedback of those that use regularly powers, whether the benefit was clear (personally, I almost never use either `Math.pow()` or `**`, so that I can’t say anything).

At least one disadvantage of an operator over a function, is that you have to think about precedence. The problem is exacerbated in JS, because (following some other languages) the unary minus has an uncanny high precedence level, confusingly very different than the one of the binary minus; so that, after having designed `**`, it was realised at the last minute that `-a**b` would be dumbly interpreted as `(-a)**b` instead of `-(a**b)` or `0-a**b`, as anybody who would be likely to actually use the operator would expect. (That particular issue was resolved in a hurry by making the parenthesis-left form a syntax error.)

—Claude

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20190815/0fefebac/attachment.html>


More information about the es-discuss mailing list