# How to determine if a number is odd in JavaScript

## How to determine if a number is odd in JavaScript

Can anyone point me to some code to determine if a number in JavaScript is even or odd?

## Solutions/Answers:

### Solution 1:

Use the below code:

``````function isOdd(num) { return num % 2;}
console.log("1 is " + isOdd(1));
console.log("2 is " + isOdd(2));
console.log("3 is " + isOdd(3));
console.log("4 is " + isOdd(4));``````

1 represents an odd number, while 0 represents an even number.

### Solution 2:

Use the bitwise `AND` operator.

``````function oddOrEven(x) {
return ( x & 1 ) ? "odd" : "even";
}
``````

If you don’t want a string return value, but rather a boolean one, use this:

``````var isOdd = function(x) { return x & 1; };
var isEven  = function(x) { return !( x & 1 ); };
``````

### Solution 3:

You could do something like this:

``````function isEven(value){
if (value%2 == 0)
return true;
else
return false;
}
``````

### Solution 4:

``````function isEven(x) { return (x%2)==0; }
function isOdd(x) { return !isEven(x); }
``````

### Solution 5:

Do I have to make an array really large that has a lot of even numbers

No. Use modulus (%). It gives you the remainder of the two numbers you are 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 if you mod any number x by 2, you get either 0 or 1 or -1. 0 would mean it’s even. Anything else would mean it’s odd.

Related:  Include the “minus-sign” into this regular expression, how?

### Solution 6:

This can be solved with a small snippet of code:

``````function isEven(value) {
if (value%2 == 0)
return true;
else
return false;
}
``````

Hope this helps 🙂

Posted on Categories Javascript