Testing whether a value is odd or even

JavascriptNumbers

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Solution 4 - Javascript

Note: there are also negative numbers.

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

where

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

Solution 5 - Javascript

Why not just do this:

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

Solution 6 - Javascript

To complete Robert Brisita's bit test .

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

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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

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

Solution 10 - Javascript

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!

Solution 11 - Javascript

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

Solution 12 - Javascript

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)

Solution 13 - Javascript

Otherway using strings because why not

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

Solution 14 - Javascript

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

Solution 15 - Javascript

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

Solution 16 - Javascript

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

Solution 17 - Javascript

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

Solution 18 - Javascript

Check if number is even in a line of code:

var iseven=(_)=>_%2==0

Solution 19 - Javascript

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

Solution 20 - Javascript

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)

Solution 21 - Javascript

This one is more simple!

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

  alert(aa[num % 2]);
       

Solution 22 - Javascript

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

Solution 23 - Javascript

if (i % 2) {
return odd numbers
}

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobGView Question on Stackoverflow
Solution 1 - JavascriptSteve MayneView Answer on Stackoverflow
Solution 2 - JavascriptRobert BrisitaView Answer on Stackoverflow
Solution 3 - JavascriptnnnnnnView Answer on Stackoverflow
Solution 4 - JavascriptIvo RenkemaView Answer on Stackoverflow
Solution 5 - JavascriptMoobiusView Answer on Stackoverflow
Solution 6 - JavascriptRaoul KiefferView Answer on Stackoverflow
Solution 7 - JavascriptbazView Answer on Stackoverflow
Solution 8 - JavascriptPandemumView Answer on Stackoverflow
Solution 9 - JavascriptFellipe SanchesView Answer on Stackoverflow
Solution 10 - JavascriptEduardo LucioView Answer on Stackoverflow
Solution 11 - JavascriptVoidView Answer on Stackoverflow
Solution 12 - JavascriptgrizminView Answer on Stackoverflow
Solution 13 - JavascriptEricView Answer on Stackoverflow
Solution 14 - JavascriptLindsay View Answer on Stackoverflow
Solution 15 - Javascriptgavr1looView Answer on Stackoverflow
Solution 16 - JavascriptMichael NellesView Answer on Stackoverflow
Solution 17 - JavascriptHamza AliView Answer on Stackoverflow
Solution 18 - JavascriptRamy HadidView Answer on Stackoverflow
Solution 19 - JavascriptSiopView Answer on Stackoverflow
Solution 20 - JavascriptgunnView Answer on Stackoverflow
Solution 21 - JavascriptAndroidManifesterView Answer on Stackoverflow
Solution 22 - Javascriptchris188View Answer on Stackoverflow
Solution 23 - JavascriptDejan MarkovicView Answer on Stackoverflow