241

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.

1

25 Answers 25

486

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.

13
  • 2
    0.1 and NaN work fine with the function above. Empty array is a bit of a pain as it equates to 0... Jun 2, 2011 at 7:41
  • 4
    @Alin - I've added a numeric check. I'm not sure I understand the scenario when you'd want an arithmetic function to explicitly handle other datatypes, but if that's what the OP wants... Jun 2, 2011 at 7:51
  • 2
    What about changing return n == parseInt(n); to return n === parseInt(n);?
    – JiminP
    Jun 2, 2011 at 7:52
  • 3
    I think I read somewhere what you should check n % 2 !== 0 when checking for odd numbers, because it isn't necessarily 1, depending on the language. EDIT: Ah, that is what the .abs call is for. Nevermind then.
    – ptf
    Dec 5, 2014 at 9:41
  • 4
    @Andy Ray - You can't say !isEven(number) for isOdd because that implies 0.1 is odd, because it isn't even. Nov 10, 2015 at 11:31
110

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.

9
  • 6
    Absolutely. Using modulus for base-2 math should be illegal ;) Jan 5, 2017 at 22:11
  • 5
    Ternary: i & 1 == 1 ? console.log("odd") : console.log("even"); Also, +1 for bit level efficiency (not as widely used in JS)
    – Jacksonkr
    Sep 15, 2017 at 15:38
  • 24
    @Jacksonkr Note that there is no “bit level efficiency” in JavaScript because all numbers are floats in JavaScript and using a bitwise operator means first converting it into an int, then performing the operation, and then converting it back to a floating point number.
    – poke
    Sep 25, 2017 at 11:25
  • 1
    @poke Correct they are of type Number but it's nice to know that there is efficiency in strongly typed languages. Sep 26, 2017 at 2:58
  • 1
    @AndrewCastellano You are testing individual bits and not the whole value of i. Any number greater than 0 will be true but it doesn't mean it is odd or even. Check out: bitwisecmd.com and see the expansion of bits according to the numbers entered. Sep 7, 2020 at 21:10
9

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);
}
4
  • 3
    For my implementation isEven(2.122e3) returns true, but isEven("2.122e3") returns false. Conversely my isEven() fails for really big numbers because JS puts them in the exponent format when converting to string for the regex test. Oh well.
    – nnnnnn
    Jun 2, 2011 at 9:44
  • @MartijnScheffer - Feel free to send me the bill for all that extra memory that you'll have to buy. Note that the question did include conversions from other types to number, and clearly the point of what I'm suggesting here is to have a simple one-line function that handles numbers and strings. Of course, as per my own comment this doesn't actually handle all possible cases, but it still may be useful - regex is the simplest way to validate user-entered data, which will be a string initially.
    – nnnnnn
    Nov 25, 2019 at 5:58
  • 1
    did i post a comment here ? i don't see it, but i can if you want one !, this is NOT a correct solution, this is hundreds of times slower, and we are talking about numbers not strings, if you want to check if a string is a valid number, and an integer that can be handled separatly. Jan 10, 2020 at 0:03
  • @MartijnScheffer - Yes, there was a comment from you, seems to have been deleted at some point since my reply. Note that the question wasn't only about numbers, the OP's code included conversions from other types. Anyway, thanks for your feedback.
    – nnnnnn
    Jan 10, 2020 at 2:02
8

Note: there are also negative numbers.

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

where

function isInteger(n)
{
   return n === parseInt(n, 10);
}
3
  • 1
    Doesn't parseInt need a radix here?
    – blablabla
    Jun 25, 2015 at 8:12
  • @blablabla Yes, not all implementations assume radix = 10.
    – Rodrigo
    Dec 5, 2016 at 15:53
  • Good citation of negative values. Robert Brisita's answer (which was added later) covers this as well.
    – Jacksonkr
    Sep 15, 2017 at 15:43
5

To complete Robert Brisita's bit test .

if ( ~i & 1 ) {
    // Even
}
5
var isOdd = x => Boolean(x % 2);
var isEven = x => !isOdd(x);
4

Why not just do this:

    function oddOrEven(num){
        if(num % 2 == 0)
            return "even";
        return "odd";
    }
    oddOrEven(num);
2
  • Or even function isEven(num) { return num % 2 == 0 }
    – chiapa
    Sep 14, 2017 at 9:57
  • 4
    or with ES6: const oddOrEven = num => num % 2 === 0 ? 'even' : 'odd'
    – enguerran
    Jan 24, 2018 at 22:21
3

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
2
  • 2
    Which is shorter as let isEven = num => num % 2 === 0. :-) But really it's no different to many other answers here.
    – RobG
    Apr 4, 2019 at 23:34
  • 1
    To expand on the other comment, (num % 2) == 0 already returns a boolean, you dont need to explicitly return afterwards.
    – Marie
    Feb 25, 2022 at 15:11
2

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
1
var isEven = function(number) {
    // Your code goes here!
    if (number % 2 == 0){
       return(true);
    }
    else{
       return(false);    
    }
};
2
  • 4
    The if ( <expression> ) return true else return false paradigm can always be simplified to return ( <expression> ) (since the expression in an if already is always a boolean one). Aug 20, 2017 at 9:35
  • saying that return isn't a function, is like saying if isn't a function, it's perfectly valid to use parenthesis when returning a value (even if they aren't not useful here) Nov 25, 2019 at 5:35
0

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!

0

The answer from Robert Brisita is great! However, I wanted the solution to be part of the JS Number prototype so that it could be called on any numeric variable rather than passing the variable into a function. Furthermore, I wanted a solution that would return null for floats as they should be considered neither even nor odd. See below for my prototype solution:

Number.prototype.even = function() {
  if (this % 1 !== 0) {
    return null
  } else {
    return (this & 1) === 0
  }
}

Number.prototype.odd = function() {
  if (this % 1 !== 0) {
    return null
  } else {
    return (this & 1) !== 0
  }
}

You can now call these methods on any numeric variable. See below for a few tests:

let zero = 0
let posOddInt = 1
let posEvenInt = 2
let posFloat = 1.5
let negOddInt = -1
let negEvenInt = -2
let negFloat = -1.5

zero.even() // true
posOddInt.even() // false
posEvenInt.even() // true
posFloat.even() // null
negOddInt.even() // false
negEvenInt.even() // true
negFloat.even() // null

zero.odd() // false
posOddInt.odd() // true
posEvenInt.odd() // false
posFloat.odd() // null
negOddInt.odd() // true
negEvenInt.odd() // false
negFloat.odd() // null
0
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var odd = (element) => element % 2 !== 0;

console.log(array.some(odd)); // true (the odd element exists)
-1

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)
0
-1

Otherway using strings because why not

function isEven(__num){
    return String(__num/2).indexOf('.') === -1;
}
-1
if (testNum == 0);
else if (testNum % 2  == 0);
else if ((testNum % 2) != 0 );
3
  • With no explanation your contribution does not have much value. It also repeats information that has already been presented in the discussion. Apr 3, 2016 at 21:11
  • Thanks Cindy! Just offering a solution!
    – Lindsay
    Aug 29, 2016 at 2:59
  • 1
    But...this doesn't actually do anything. Shouldn't it return something?
    – nnnnnn
    Oct 13, 2016 at 12:41
-1

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

1
  • 2
    While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations!
    – Filnor
    Mar 28, 2018 at 13:15
-1
var num = someNumber
    isEven;
parseInt(num/2) === num/2 ? isEven = true : isEven = false;
-1

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

1
  • While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
    – user12867493
    Jun 24, 2020 at 12:02
-1

Check if number is even in a line of code:

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

-3

This one is more simple!

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

  alert(aa[num % 2]);
1
  • 1
    That will return undefined for num = -1 Dec 10, 2015 at 4:01
-3

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

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)
3
  • isOdd('5')) returns true. isEven('5') also returns true. isOdd(NaN) throws an error. :-(
    – RobG
    Oct 31, 2017 at 1:39
  • Fixed isEven('5'). isOdd(NaN) probably should throw an error.
    – gunn
    Oct 31, 2017 at 3:08
  • 1
    The script host should not be handling the error, the function should. I was always told a core dump is not a normal termination. ;-)
    – RobG
    Oct 31, 2017 at 7:15
-3
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

2
  • Or return parseInt(n)%2===0?true:parseInt(n)===0. but then again, this is the same as many of the other answers already here. Jun 4, 2019 at 21:48
  • 1
    Or return parseInt(n)%2 === 0 || parseInt(n) === 0. But why parseInt? That returns true for values like "32foo" and 12.5, which are not even.
    – RobG
    Jun 5, 2019 at 7:20
-3
if (i % 2) {
return odd numbers
}

if (i % 2 - 1) {
return even numbers
}
2
  • 1
    when will the reminder of dividing any number by 2 be 2?
    – user85421
    Sep 23, 2019 at 15:01
  • Hm, yea you have right. I miss write % 2 == 2. My bad. Sep 24, 2019 at 16:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.