[javascript] Testing whether a value is odd or even

I decided to create simple isEven and isOdd function with a very simple algorithm:

function isEven(n) {
  n = Number(n);
  return n === 0 || !!(n && !(n%2));
}

function isOdd(n) {
  return isEven(Number(n) + 1);
}

That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.

// Returns true if:
//
//    n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string

(function (global) {

  function basicTests(n) {

    // Deal with empty string
    if (n === '') 
      return false;

    // Convert n to Number (may set to NaN)
    n = Number(n);

    // Deal with NaN
    if (isNaN(n)) 
      return false;

    // Deal with infinity - 
    if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
      return false;

    // Return n as a number
    return n;
  }

  function isEven(n) {

    // Do basic tests
    if (basicTests(n) === false)
      return false;

    // Convert to Number and proceed
    n = Number(n);

    // Return true/false
    return n === 0 || !!(n && !(n%2));
  }
  global.isEven = isEven;

  // Returns true if n is an integer and (n+1) is even
  // Returns false if n is not an integer or (n+1) is not even
  // Empty string evaluates to zero so returns false (zero is even)
  function isOdd(n) {

    // Do basic tests
    if (basicTests(n) === false)
      return false;

    // Return true/false
    return n === 0 || !!(n && (n%2));
  }
  global.isOdd = isOdd;

}(this));

Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?

There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript.

This question is related to javascript numbers

The answer is


var isEven = function(number) {
    // Your code goes here!
    if (number % 2 == 0){
       return(true);
    }
    else{
       return(false);    
    }
};

This one is more simple!

  var num = 3 //instead get your value here
  var aa = ["Even", "Odd"];

  alert(aa[num % 2]);

var num = someNumber
    isEven;
parseInt(num/2) === num/2 ? isEven = true : isEven = false;

How about the following? I only tested this in IE, but it was quite happy to handle strings representing numbers of any length, actual numbers that were integers or floats, and both functions returned false when passed a boolean, undefined, null, an array or an object. (Up to you whether you want to ignore leading or trailing blanks when a string is passed in - I've assumed they are not ignored and cause both functions to return false.)

function isEven(n) {
   return /^-?\d*[02468]$/.test(n);
}

function isOdd(n) {
   return /^-?\d*[13579]$/.test(n);
}

Note: there are also negative numbers.

function isOddInteger(n)
{
   return isInteger(n) && (n % 2 !== 0);
}

where

function isInteger(n)
{
   return n === parseInt(n, 10);
}

_x000D_
_x000D_
for(var a=0; a<=20;a++){
   if(a%2!==0){
       console.log("Odd number "+a);
   }
}

for(var b=0; b<=20;a++){
    if(b%2===0){
        console.log("Even number "+b);  
    }     
 }
_x000D_
_x000D_
_x000D_


var isOdd = x => Boolean(x % 2);
var isEven = x => !isOdd(x);

Why not just do this:

    function oddOrEven(num){
        if(num % 2 == 0)
            return "even";
        return "odd";
    }
    oddOrEven(num);

To complete Robert Brisita's bit test .

if ( ~i & 1 ) {
    // Even
}

Otherway using strings because why not

function isEven(__num){
    return String(__num/2).indexOf('.') === -1;
}

We just need one line of code for this!

Here a newer and alternative way to do this, using the new ES6 syntax for JS functions, and the one-line syntax for the if-else statement call:

const isEven = num => ((num % 2) == 0) ? true : false;

alert(isEven(8));  //true
alert(isEven(9));  //false
alert(isEven(-8)); //true

To test whether or not you have a odd or even number, this also works.

const comapare = x => integer(checkNumber(x));

function checkNumber (x) {
   if (x % 2 == 0) {
       return true;
   } 
   else if (x % 2 != 0) {
       return false;
    }
}

function integer (x) {
   if (x) {
       console.log('even');
   } 
   else {
       console.log('odd');
    }
}

I prefer using a bit test:

if(i & 1)
{
    // ODD
}
else
{
    // EVEN
}

This tests whether the first bit is on which signifies an odd number.


if (i % 2) {
return odd numbers
}

if (i % 2 - 1) {
return even numbers
}

Using modern javascript style:

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

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

A few

x % 2 == 0; // Check if even

!(x & 1); // bitmask the value with 1 then invert.

((x >> 1) << 1) == x; // divide value by 2 then multiply again and check against original value

~x&1; // flip the bits and bitmask

A simple modification/improvement of Steve Mayne answer!

function isEvenOrOdd(n){
    if(n === parseFloat(n)){
        return isNumber(n) && (n % 2 == 0);
    }
    return false;
}

Note: Returns false if invalid!


if (testNum == 0);
else if (testNum % 2  == 0);
else if ((testNum % 2) != 0 );

function isEven(n) {return parseInt(n)%2===0?true:parseInt(n)===0?true:false}

when 0/even wanted but

isEven(0) //true
isEven(1) //false
isEven(2) //true
isEven(142856) //true
isEven(142856.142857)//true
isEven(142857.1457)//false

?


Different way:

var isEven = function(number) {
  // Your code goes here!
  if (((number/2) - Math.floor(number/2)) === 0) {return true;} else {return false;};
};

isEven(69)

Maybe this? if(ourNumber % 2 !== 0)