Ok, I was hoping to have a bit more hoopla about this but at the moment this is all I can muster. So happy 10,000th! it was a few days ago but better late than never.
I'm hoping to do a full redesign soon of the layout, but it'll have to wait for the moment.
Anyway here's a little trip back to the very first post - Barebones Daily.
A blog about product, movie, and book reviews. Also in the works, a platform for design, programming and discussions of the like
Tuesday, August 27, 2013
Sunday, August 4, 2013
Understanding Modulo operator in Javascript conditionals
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 {...
}
Related articles
Subscribe to:
Posts (Atom)