According to Wikipedia, the modulo operator (remainder of integer division) on n should yield a result between 0 and n-1.
This is indeed the case in python:
print(-1%5) # outputs 4
In Ruby:
puts -1%5 # outputs 4
In Haskell
main = putStrLn $ show $ mod (-1) 5
But inJavascript:
console.log(-1%5);
The result is -1 !!
Why is that ? is there logic behind this design decision ?
While -1 is equivalent to 4 modulo 5, negative values makes it harder to use as indices.
For example:
arr[x%5]
would always be a valid expression in python and Ruby when the array length is more than 5, but in the Javascript, this is an exception waiting to happen.
When either a or n is negative, the naive definition breaks down and programming languages differ in how these values are defined.So it's not like progamming languages are in breach of it as you also claim.arr[x%5]isan exception waiting to happenin JS - if you pass in a negative number you'll get a negative result, so you'll getundefined. If the operator did indeed work like python or whatever, then it will give you a random element from the array. So you could have a bug and never find it until way later because it seems like it works.%is treated as "give me the remainder". That seems to be the rationale.%nfunction hasnpossible values when applied in other languages (e.g.python,ruby,haskell) but injavascriptit has2n-1possible values