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?

9

31 Answers

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.

11

Use the bitwise AND operator.

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

function checkNumber(argNumber) {
  document.getElementById("result").innerHTML = "Number " + argNumber + " is " + oddOrEven(argNumber);
}
 
checkNumber(17);
<div id="result" style="font-size:150%;text-shadow: 1px 1px 2px #CE5937;" ></div>

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 ); };
16

You could do something like this:

function isEven(value){
    if (value%2 == 0)
        return true;
    else
        return false;
}
5
function isEven(x) { return (x%2)==0; }
function isOdd(x) { return !isEven(x); }
0

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.

0

This can be solved with a small snippet of code:

function isEven(value) {
    return !(value % 2)
}

Hope this helps :)

0

In ES6:

const isOdd = num => num % 2 == 1;
2

With bitwise, codegolfing:

var isEven=n=>(n&1)?"odd":"even";
2

Like many languages, Javascript has a modulus operator %, that finds the remainder of division. If there is no remainder after division by 2, a number is even:

// this expression is true if "number" is even, false otherwise
(number % 2 == 0)

Similarly, if there is a remainder of 1 after division by 2, a number is odd:

// this expression is true if "number" is odd, false otherwise
(number % 2 == 1)

This is a very common idiom for testing for even integers.

1

Use my extensions :

Number.prototype.isEven=function(){
     return this % 2===0;
};

Number.prototype.isOdd=function(){
     return !this.isEven();
}

then

var a=5; 
 a.isEven();

==False

 a.isOdd();

==True

if you are not sure if it is a Number , test it by the following branching :

if(a.isOdd){
    a.isOdd();
}

UPDATE :

if you would not use variable :

(5).isOdd()

Performance :

It turns out that Procedural paradigm is better than OOP paradigm . By the way , i performed profiling in this FIDDLE . However , OOP way is still prettiest .

3

A simple function you can pass around. Uses the modulo operator %:

var is_even = function(x) {
    return !(x % 2); 
}

is_even(3)
false
is_even(6)
true
1
if (X % 2 === 0){
} else {
}

Replace X with your number (can come from a variable). The If statement runs when the number is even, the Else when it is odd.

If you just want to know if any given number is odd:

if (X % 2 !== 0){
}

Again, replace X with a number or variable.

   <script>
        function even_odd(){
            var num =   document.getElementById('number').value;

            if ( num % 2){
                document.getElementById('result').innerHTML = "Entered Number is Odd";
            }
            else{
                document.getElementById('result').innerHTML = "Entered Number is Even";
            }
        }
    </script>
</head>
<body>
    <center>
        <div id="error"></div>
        <center>
            <h2> Find Given Number is Even or Odd </h2>
            <p>Enter a value</p>
            <input type="text" id="number" />
            <button onclick="even_odd();">Check</button><br />
            <div id="result"><b></b></div>
        </center>
    </center>
</body>

Subtract 2 to it recursively until you reach either -1 or 0 (only works for positive integers obviously) :)

2

You can use a for statement and a conditional to determine if a number or series of numbers is odd:

for (var i=1; i<=5; i++) 
if (i%2 !== 0) {
    console.log(i)
}

This will print every odd number between 1 and 5.

0

Just executed this one in Adobe Dreamweaver..it works perfectly. i used if (isNaN(mynmb))

to check if the given Value is a number or not, and i also used Math.abs(mynmb%2) to convert negative number to positive and calculate

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head>

</head>
<body bgcolor = "#FFFFCC">
    <h3 align ="center"> ODD OR EVEN </h3><table cellspacing = "2" cellpadding = "5" bgcolor="palegreen">
        <form name = formtwo>
            <td align = "center">
                <center><BR />Enter a number: 
                    <input type=text id="enter" name=enter maxlength="10" />
                    <input type=button name = b3 value = "Click Here" onClick = compute() />
                      <b>is<b> 
                <input type=text id="outtxt" name=output size="5" value="" disabled /> </b></b></center><b><b>
                <BR /><BR />
            </b></b></td></form>
        </table>

    <script type='text/javascript'>

        function compute()
        {
          var enter = document.getElementById("enter");
          var outtxt = document.getElementById("outtxt");

          var mynmb = enter.value;
          if (isNaN(mynmb)) 
          { 
            outtxt.value = "error !!!"; 
            alert( 'please enter a valid number');
            enter.focus();
            return;
          }
          else 
          { 
             if ( mynmb%2 == 0 ) { outtxt.value = "Even"; }  
             if ( Math.abs(mynmb%2) == 1 ) { outtxt.value = "Odd"; }
          }
        }

    </script>
</body>
</html>

When you need to test if some variable is odd, you should first test if it is integer. Also, notice that when you calculate remainder on negative number, the result will be negative (-3 % 2 === -1).

function isOdd(value) {
  return typeof value === "number" && // value should be a number
    isFinite(value) &&                // value should be finite
    Math.floor(value) === value &&    // value should be integer
    value % 2 !== 0;                  // value should not be even
}

If Number.isInteger is available, you may also simplify this code to:

function isOdd(value) {
  return Number.isInteger(value)      // value should be integer
    value % 2 !== 0;                  // value should not be even
}

Note: here, we test value % 2 !== 0 instead of value % 2 === 1 is because of -3 % 2 === -1. If you don't want -1 pass this test, you may need to change this line.

Here are some test cases:

isOdd();         // false
isOdd("string"); // false
isOdd(Infinity); // false
isOdd(NaN);      // false
isOdd(0);        // false
isOdd(1.1);      // false
isOdd("1");      // false
isOdd(1);        // true
isOdd(-1);       // true

Using % will help you to do this...

You can create couple of functions to do it for you... I prefer separte functions which are not attached to Number in Javascript like this which also checking if you passing number or not:

odd function:

var isOdd = function(num) {
  return 'number'!==typeof num ? 'NaN' : !!(num % 2);
};

even function:

var isEven = function(num) {
  return isOdd(num)==='NaN' ? isOdd(num) : !isOdd(num);
};

and call it like this:

isOdd(5); // true
isOdd(6); // false
isOdd(12); // false
isOdd(18); // false
isEven(18); // true
isEven('18'); // 'NaN'
isEven('17'); // 'NaN'
isOdd(null); // 'NaN'
isEven('100'); // true

A more functional approach in modern javascript:

const NUMBERS = "nul one two three four five six seven ocho nueve".split(" ")

const negate = f=> (...args)=> !f(...args)
const isOdd  = n=> NUMBERS[n % 10].indexOf("e")!=-1
const isEven = negate(isOdd)
0

One liner in ES6 just because it's clean.

const isEven = (num) => num % 2 == 0;

Many people misunderstand the meaning of odd

  • isOdd("str") should be false.
    Only an integer can be odd.
  • isOdd(1.223) and isOdd(-1.223) should be false.
    A float is not an integer.
  • isOdd(0) should be false.
    Zero is an even integer ().
  • isOdd(-1) should be true.
    It's an odd integer.
Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.