Sunday, August 4, 2013

Understanding Modulo operator in Javascript conditionals

Titel WikiBook JavaScript
Titel WikiBook JavaScript (Photo credit: Wikipedia)
I'm just trying to clear up an issue I've had with using logic conditionals and the Modulo operator  '%'. Assuming it is language independent, it might be relevant to other languages. However in this discourse, it is primarily JavaScript focused.

Now the Modulo operator is used to find the remainder between two numbers, like so:
 4 % 6  yields a remainder of 4
14 % 4 yields a remainder of 2 etcetera

Now that's very straight forward. When it comes to using it as a test in an conditional such as an if statement, i.e.
 if (4 % 1) {...
    } else {...
the else branch of the conditional would run. Now why would that be?

Well the Modulo operator works by dividing the first number by the second one, so 4 divided 1 would be 4, but the % operator would only return the remainder which in this would be nothing. So that would translate to zero which in most cases is considered equivalent to false.

So to further illustrate the point, to check if a number is divisible by 3, we would rationalise:
 if (n % 3) {...
    } else {...
would mean the first conditional branch tests the number NOT being divisible by three. This is because, in order for the condition to be true would mean returning any remainder which would mean the number will not divide by three evenly. And any value other than a zero would translate to the condition as being true in JavaScript.

Enhanced by Zemanta

No comments: