Javascript Quick Tips - odd or even?
Alternating the background color of HTML table rows is usually handled by the server. Sometimes however, this has to be done client-wise (when using this script for example). One of the easiest and cleanest way to handle this issue is by determining whether the row is odd or even.
This is easily done in javascript using the modulo operator % which simply return the remainder of a division of one number by another:
10 % 3
// returns 1 (the biggest integer divisible by 3 being 9, the remainder is 1)
As we all know, the property of even numbers is to be exactly divisible by 2, so
num % 2 // will always return 0 if num is even
On the contrary, odd numbers will always have a remainder of 1 when divided by 2.
We now have a short and simple method to determine whether a number is even or odd; lets extract it into a reusable function. As we will mostly use this function in conditional arguments we would want it return a result which can be directly evaluated to either true or false. We will therefore build two functions, one will will test to see if a given number is odd… and the other if it is even.
Lets start by the latter:
function isEven(num) {
return !(num % 2);
}
isEven(2) // returns 'true'
isEven(3) // returns 'false'
That’s it! Pretty and concise. As JavaScript evaluates the integer 0 as false and any other integer as true, !(num % 2) will directly return true if the number is even and false otherwise
From there, is isOdd() is dead easy; it’s just the opposite of isEven():
function isOdd(num) {
return !isEven(num);
}
isEven(2) // returns 'false'
isEven(3) // returns 'true'