0
votes

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.

1
You reference Wikipedia and yet it clearly states 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. - VLAZ
It is evident that this is the case, the question is why ? - Uri Goren
Also I don't see how arr[x%5] is an exception waiting to happen in JS - if you pass in a negative number you'll get a negative result, so you'll get undefined. 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. - VLAZ
As for "why" that's the case - the dupe you were linked to last time did have the answer - % is treated as "give me the remainder". That seems to be the rationale. - VLAZ
The end result is that the %n function has n possible values when applied in other languages (e.g. python,ruby,haskell) but in javascript it has 2n-1 possible values - Uri Goren

1 Answers

2
votes

If by "modulus" you understand the remainder of the Euclidean division as common in mathematics, the % operator is not the modulo operator. It rather is called the remainder operator, whose result always has the same sign as the dividend. (In Haskell, the rem function does this).

This behaviour is pretty common amongst programming languages, notably also in C and Java from which the arithmetic conventions of JavaScript were inspired.