236

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.

JJJ
  • 32,902
  • 20
  • 89
  • 102
RobG
  • 142,382
  • 31
  • 172
  • 209
  • Possible duplicate of [How to determine if a number is odd in JavaScript](http://stackoverflow.com/questions/5016313/how-to-determine-if-a-number-is-odd-in-javascript) – nyedidikeke May 11 '17 at 18:38

23 Answers23

478

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.

Steve Mayne
  • 22,285
  • 4
  • 49
  • 49
  • @Steve Yes, but JS has some special issues when `value` is not a number, or even if it's a number. Ex.: `0.1%2`, `NaN%2`, `[]%2`, etc. What you wrote in the answer, he already knows it. – Alin Purcaru Jun 02 '11 at 07:29
  • @Steve Accordin to your tests `[]` is even. – Alin Purcaru Jun 02 '11 at 07:40
  • 2
    `0.1` and `NaN` work fine with the function above. Empty array is a bit of a pain as it equates to 0... – Steve Mayne Jun 02 '11 at 07: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... – Steve Mayne Jun 02 '11 at 07:51
  • 2
    What about changing `return n == parseInt(n);` to `return n === parseInt(n);`? – JiminP Jun 02 '11 at 07:52
  • I've added that option to the end of my answer - thanks JiminP – Steve Mayne Jun 02 '11 at 08:04
  • Pretty good, fails for `isOdd('2.123e3')` but a more robust `isNumber` function would fix that. Under consideration. – RobG Jun 02 '11 at 09:12
  • Yeah, I like that. *isNumber* still needs a bit of work, don't want '' or ' ' coerced to 0, but otherwise seems fine. There was an answer that returned *true* and *false* only where even/odd made sense and *undefined* otherwise, I liked that but it seems to have been removed. Might modify the above for that as it seems logical to return *undefined* for `isEven(Infinity)`. – RobG Jun 02 '11 at 23:59
  • @Steve - the function should handle non-numeric data types sensibly, i.e. not throw an error. I've made the `isNumber` test more specific to my requirements and if it returns false, *isOdd* and *isEven* return `undefined`. So `isOdd([1])` is `true` and `isOdd([1,2])` is `undefined`, so still falsey but the different returned value should help with debugging. – RobG Jun 03 '11 at 01:19
  • This fails for negative integers. See my answer below. – Ivo Renkema Jan 29 '14 at 14:09
  • 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 05 '14 at 09:41
  • 4
    @Andy Ray - You can't say !isEven(number) for isOdd because that implies 0.1 is odd, because it isn't even. – Steve Mayne Nov 10 '15 at 11:31
  • A shorter solution: `n % 2 === 0 ? console.log("is Even") : console.log("is Odd");` – hailton May 04 '21 at 15:44
108

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.

Robert Brisita
  • 5,461
  • 3
  • 36
  • 35
  • Only useful if you know *i* is a number to start with. Non–numbers should return *undefined* (or maybe throw an error, but *undefined* seems sensible). – RobG Mar 11 '14 at 00:15
  • Agreed 'undefined' would be a good return on data types other than numbers. This was just a quick and dirty example of the conditional and not a full implementation. – Robert Brisita Mar 11 '14 at 20:20
  • 5
    Absolutely. Using modulus for base-2 math should be illegal ;) – aceofspades Jan 05 '17 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 '17 at 15:38
  • 23
    @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 '17 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. – Robert Brisita Sep 26 '17 at 02:58
  • @mbomb007 Just saying that while it works in favor in this case, it might not work with other bitwise tricks that people might be used to from other languages (e.g. bit shifting vs. dividing). – poke Feb 13 '18 at 20:06
  • I confirmed that it works, but why wouldn't any i > 0 resolve to true? since any i > 0 is truthy? for example, why wouldn't (2 & 1) => (T & T) => T? I know I'm missing something fundamental here... – Andrew Castellano Sep 07 '20 at 19:02
  • 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: http://bitwisecmd.com/ and see the expansion of bits according to the numbers entered. – Robert Brisita Sep 07 '20 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);
}
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • 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 02 '11 at 09: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 '19 at 05: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. – Martijn Scheffer Jan 10 '20 at 00: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 '20 at 02: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);
}
Bart Riordan
  • 436
  • 3
  • 8
  • 23
Ivo Renkema
  • 2,188
  • 1
  • 29
  • 40
5

To complete Robert Brisita's bit test .

if ( ~i & 1 ) {
    // Even
}
Raoul Kieffer
  • 51
  • 1
  • 2
5
var isOdd = x => Boolean(x % 2);
var isEven = x => !isOdd(x);
baz
  • 1,317
  • 15
  • 10
4

Why not just do this:

    function oddOrEven(num){
        if(num % 2 == 0)
            return "even";
        return "odd";
    }
    oddOrEven(num);
Moobius
  • 57
  • 1
  • 4
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
Fellipe Sanches
  • 7,395
  • 4
  • 32
  • 33
  • 2
    Which is shorter as `let isEven = num => num % 2 === 0`. :-) But really it's no different to many other answers here. – RobG Apr 04 '19 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 '22 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
mwilson
  • 12,295
  • 7
  • 55
  • 95
Void
  • 21
  • 1
1
var isEven = function(number) {
    // Your code goes here!
    if (number % 2 == 0){
       return(true);
    }
    else{
       return(false);    
    }
};
Pandemum
  • 19
  • 1
  • 4
    The `if ( ) return true else return false` paradigm can _always_ be simplified to `return ( )` (since the expression in an `if` already is always a boolean one). – Gerold Broser Aug 20 '17 at 09: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) – Martijn Scheffer Nov 25 '19 at 05: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!

Eduardo Lucio
  • 1,771
  • 2
  • 25
  • 43
-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)
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
grizmin
  • 149
  • 5
-1

Otherway using strings because why not

function isEven(__num){
    return String(__num/2).indexOf('.') === -1;
}
Eric
  • 9,870
  • 14
  • 66
  • 102
-1
if (testNum == 0);
else if (testNum % 2  == 0);
else if ((testNum % 2) != 0 );
-1

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

gavr1loo
  • 1
  • 1
  • 2
    While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) 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 '18 at 13:15
-1
var num = someNumber
    isEven;
parseInt(num/2) === num/2 ? isEven = true : isEven = false;
Michael Nelles
  • 5,426
  • 8
  • 41
  • 57
-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);  
    }     
 }
Hamza Ali
  • 32
  • 6
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) 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. –  Jun 24 '20 at 12:02
-1

Check if number is even in a line of code:

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

Ramy Hadid
  • 120
  • 6
-3

This one is more simple!

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

  alert(aa[num % 2]);
Linus Oleander
  • 17,746
  • 15
  • 69
  • 102
-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');
    }
}
Siop
  • 1
  • 2
-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)
gunn
  • 8,999
  • 2
  • 24
  • 24
  • `isOdd('5'))` returns true. `isEven('5')` also returns true. `isOdd(NaN)` throws an error. :-( – RobG Oct 31 '17 at 01:39
  • Fixed `isEven('5')`. `isOdd(NaN)` probably should throw an error. – gunn Oct 31 '17 at 03: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 '17 at 07: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

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
chris188
  • 1
  • 1
  • 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. – Heretic Monkey Jun 04 '19 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 05 '19 at 07:20
-3
if (i % 2) {
return odd numbers
}

if (i % 2 - 1) {
return even numbers
}
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345