Test for Even / Odd Numbers in Javascript


/ Published in: JavaScript
Save to your folder(s)

One of those common tools that's easy to forget about is the Modulus operator (%), which returns the remainder of a division operation.

If you divide some number by two, a remainder of 0 indicates an even number, while a remainder of 1 indicates an odd number.


Copy this code and paste it in your HTML
  1. var isEven = function(someNumber){
  2. return (someNumber%2 == 0) ? true : false;
  3. };
  4.  
  5. alert(isEven(64)); // Alerts "true".
  6.  
  7. alert(isEven(97)); // Alerts "false".

URL: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Arithmetic_Operators

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.