Problem
Can anyone point me to some code to determine if a number in JavaScript is even or odd?
Asked by Jannie Theunissen
Solution #1
Use the code below:
The number 1 is an odd number, while the number 0 is an even number.
Answered by Chii
Solution #2
Use the bitwise AND operator to combine two bits.
If you want a boolean return value instead of a string, use this:
var isOdd = function(x) { return x & 1; };
var isEven = function(x) { return !( x & 1 ); };
Answered by 13 revs, 3 users 80%
Solution #3
This is an example of what you could do:
function isEven(value){
if (value%2 == 0)
return true;
else
return false;
}
Answered by TNC
Solution #4
function isEven(x) { return (x%2)==0; }
function isOdd(x) { return !isEven(x); }
Answered by CloudyMarble
Solution #5
No, use modulus instead ( percent ). It returns the difference between the two numbers you’re dividing.
Ex. 2 % 2 = 0 because 2/2 = 1 with 0 remainder.
Ex2. 3 % 2 = 1 because 3/2 = 1 with 1 remainder.
Ex3. -7 % 2 = -1 because -7/2 = -3 with -1 remainder.
This means that when you multiply any number x by 2, you get 0 or 1 or -1. It’s even if the number is zero. Anything else would indicate that something is strange.
Answered by Isaac Fife
Post is based on https://stackoverflow.com/questions/5016313/how-to-determine-if-a-number-is-odd-in-javascript