Titel WikiBook JavaScript (Photo credit: Wikipedia) |
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
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?} else {...
}
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.} else {...
}
No comments:
Post a Comment