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.
143
votes
@SilentGhost: do people really get jQuery homework nowadays?
- Andy E
don't know about that Andy, but people surely know how to mess up their tags.
- SilentGhost
@OP: jQuery isn't the answer to everything you could possibly want to do in JavaScript ;)
- Mike Atlas
@Mike Wrong! You should use the jQuery basic arithmetic plugin for that! Thats the way to go... :P (Irony)
- Pablo Cabrera
12 Answers
29
votes
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);
};
})();
13
votes
12
votes
11
votes
3
votes
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');
}
}
2
votes
2
votes
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.