162

How do I figure out if a variable is divisible by 2? Furthermore I need do a function if it is and do a different function if it is not.

Naftali
  • 144,921
  • 39
  • 244
  • 303
sadmicrowave
  • 39,964
  • 34
  • 108
  • 180

12 Answers12

390

Use modulus:

// Will evaluate to true if the variable is divisible by 2
variable % 2 === 0  
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 40
    love it! simple, easy, and you didn't make me feel like an idiot for asking the question...which (for all the others who don't already know) is a big deal to new jQuery/Javascript developers. – sadmicrowave May 13 '10 at 11:54
  • 7
    @sadmicrowave: we all start out as beginners at some point. The real problem is the lack of informative tutorials out there. The tutorials for absolute beginners should clarify the difference between JavaScript and jQuery and they just dive straight into the jQuery stuff. – Andy E May 13 '10 at 12:03
  • 4
    The first code I ever wrote was in JavaScript, and that was a "welcome" alert box popup. The year was 1997 and it was for my Geocities homepage. We definitely all start somewhere (some formal training helps, too, though). – Mike Atlas May 13 '10 at 16:23
  • shouldn't it be: variable % 2 == 0 Educate me if I am wrong. – Sean Tank Garvey Jun 12 '20 at 18:56
  • @SeanTankGarvey the modulo operator will return an integer. So a strict comparison works in this case. – Mathyou Sep 12 '20 at 13:17
  • Doesn't seem to work when using floats, for instance: `1 % 0.1` returns `0.09999999999999995` instead of `0`. – Ander Oct 13 '22 at 07:53
28

Seriously, there's no jQuery plugin for odd/even checks?

Well, not anymore - releasing "Oven" a jQuery plugin under the MIT license to test if a given number is Odd/Even.

Source code is also available at http://jsfiddle.net/7HQNG/

Test-suites are available at http://jsfiddle.net/zeuRV/

(function() {
    /*
     * isEven(n)
     * @args number n
     * @return boolean returns whether the given number is even
     */
    jQuery.isEven = function(number) {
        return number % 2 == 0;
    };

    /* isOdd(n)
     * @args number n
     * @return boolean returns whether the given number is odd
     */
    jQuery.isOdd = function(number) {
        return !jQuery.isEven(number);
    };
})();​
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • 9
    Wow. Funny, but you do realise someone will actually use this? – Tim Down May 13 '10 at 08:52
  • 7
    @Tim Down: I wonder if anyone uses that [jQuery basic arithmetic plugin](http://www.reddit.com/r/programming/comments/buosj/add_a_number_to_another_number_in_javascript_img/c0on5ev)? Next on the list, a jQuery random number generator ;-) – Andy E May 13 '10 at 08:58
  • 9
    There is so much that jQuery can do, like creating variables, functions, etc., that is still being done with *raw JavaScript*. Just unbelievable ;-) – Anurag May 13 '10 at 09:10
  • 5
    @Andy - ROFL at the that link and the SO image - http://www.doxdesk.com/img/updates/20091116-so-large.gif I guess the "use jQuery" answer is gonna reach an all-time high in Javascript now :) – Anurag May 13 '10 at 09:20
  • You do have word document explain use me it? @Anurag – Todd Nov 14 '14 at 14:18
  • You forgot an import edge case, though. `$.isEven("foo");` Surprised that made it past your test suites. – Todd Nov 14 '14 at 14:20
  • @Todd - great point, I totally missed that case. Will update the tests to ensure we don't regress further. Also I think there is a tricky edge-case that I haven't been able to figure out: `$.isEven("odd")`. Any help is greatly appreciated. – Anurag May 22 '15 at 02:02
14

You don't need jQuery. Just use JavaScript's Modulo operator.

Mike Atlas
  • 8,193
  • 4
  • 46
  • 62
  • 6
    http://www.doxdesk.com/img/updates/20091116-so-large.gif, for those of you that don't understand what @AlexCoplan is talking about – markasoftware Feb 25 '14 at 03:57
13

You can use the modulus operator like this, no need for jQuery. Just replace the alerts with your code.

var x = 2;
if (x % 2 == 0)
{
  alert('even');
}
else
{
  alert('odd')
}
wsanville
  • 37,158
  • 8
  • 76
  • 101
12

You can do it in a better way (up to 50 % faster than modulo operator):

odd: x & 1 even: !(x & 1)

Reference: High Performance JavaScript, 8. ->Bitwise Operators

Klapaucjusz TF
  • 181
  • 2
  • 8
9

You can also:

if (x & 1)
 itsOdd();
else
 itsEven();
Alex K.
  • 171,639
  • 30
  • 264
  • 288
8

Hope this helps.

let number = 7;

if(number%2 == 0){      

  //do something;
  console.log('number is Even');  

}else{

  //do otherwise;
  console.log('number is Odd');

}

Here is a complete function that will log to the console the parity of your input.

const checkNumber = (x) => {
  if(number%2 == 0){      

    //do something;
    console.log('number is Even');  

  }else{

    //do otherwise;
    console.log('number is Odd');

  }
}
Edgar256
  • 702
  • 9
  • 13
6
if (x & 1)
 itIsOddNumber();
else
 itIsEvenNumber();
4
var x = 2;
x % 2 ? oddFunction() : evenFunction();
Pablo Cabrera
  • 5,749
  • 4
  • 23
  • 28
  • I think this code is wrong/flawed. You are declaring a value for the variable x (specifically making x always equivalent to the number 2)..first error. Then, your next line simply says if the variable x can be divided by 2, then do the oddFunction, else/if-not do the evenFunction... The problem with this approach is that it will always produce the evenFunction - never the oddFunction - that's another problem/error. Please educate me if I am wrong. – Sean Tank Garvey Jun 12 '20 at 18:51
2

Please write the following code in your console:

var isEven = function(deep) {

  if (deep % 2 === 0) {
        return true;  
    }
    else {
        return false;    
    }
};
isEven(44);

Please Note: It will return true, if the entered number is even otherwise false.

  • 1
    thanks for the answer but this is essentially the same as the accepted answer, you just wrapped it in a function. Anyway, thanks for contributing – sadmicrowave Mar 01 '17 at 15:19
2

Use Modulus, but.. The above accepted answer is slightly inaccurate. I believe because x is a Number type in JavaScript that the operator should be a double assignment instead of a triple assignment, like so:

x % 2 == 0

Remember to declare your variables too, so obviously that line couldn't be written standalone. :-) Usually used as an if statement. Hope this helps.

-2

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

array.each { |x| puts x if x % 2 == 0 }

ruby :D

2 4 6 8 10

SteveO
  • 15
  • 1