Home » Javascript » Testing whether a value is odd or even

Testing whether a value is odd or even

Posted by: admin November 30, 2017 Leave a comment

Questions:

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.

Edit

A code review tag was added, but I’m not after a code review. I posted the code simply so others could see where I was up to, not as something to review. Answers posted so far seem to get that.

Edit 2

A final function, based on Steve’s answer:

// Use abstract equality == for "is number" test
function isEven(n) {
  return n == parseFloat(n)? !(n%2) : void 0;
}

// Use strict equality === for "is number" test
function isEvenStrict(n) {
  return n === parseFloat(n)? !(n%2) : void 0;
}

Anything that is not a number returns undefined, numbers return either true or false. It could be one function with a strict flag, but I think the strict comparison is not really required.

Answers:

Use modulus:

function isEven(n) {
   return n % 2 == 0;
}

function isOdd(n) {
   return Math.abs(n % 2) == 1;
}

You can check that any value in Javascript can be coerced to a number with:

Number.isFinite(parseFloat(n))

This check should preferably be done outside the isEven and isOdd functions, so you don’t have to duplicate error handling in both functions.

Questions:
Answers:

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.

Questions:
Answers:

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

Questions:
Answers:

Note: there are also negative numbers.

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

where

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

Questions:
Answers:

Why not just do this:

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

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

Questions:
Answers:

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!

Questions:
Answers:

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)

Questions:
Answers:

Otherway using strings because why not

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

Questions:
Answers:
if (testNum == 0);
else if (testNum % 2  == 0);
else if ((testNum % 2) != 0 );

Questions:
Answers:

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

Questions:
Answers:

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)

Questions:
Answers:

This one is more simple!

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

  alert(aa[num % 2]);