How to determine if a variable is divisible by 2? In addition, I need a function, if one exists, and execute another function if it is not.
Use module:
// Will evaluate to true if the variable is divisible by 2 variable % 2 === 0
Seriously, there is no jQuery plugin for odd / even checks?
Well, no more - releasing the βOvenβ jQuery plugin under the MIT license to check if this number is odd / even.
Source code is also available at http://jsfiddle.net/7HQNG/
Test kits 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); }; })();β
You do not need jQuery. Just use the JavaScript modulo operator.
You can use a module operator like this, no jQuery needed. Just replace alerts with your code.
alerts
var x = 2; if (x % 2 == 0) { alert('even'); } else { alert('odd') }
You can do it better (50% faster than the modulo operator):
odd: x and 1 even :! (x and 1)
Link: high-performance JavaScript, 8. β Bitwise operators
You also can:
if (x & 1) itsOdd(); else itsEven();
var x = 2; x % 2 ? oddFunction() : evenFunction();
if (x & 1) itIsOddNumber(); else itIsEvenNumber();
Please write the following code in the console:
var isEven = function(deep) { if (deep % 2 === 0) { return true; } else { return false; } }; isEven(44);
Note: It will return true if the entered number is otherwise incorrect.
Use the module, but .. The answer above is a bit inaccurate. I believe because x is the Number type in JavaScript, which should be a dual purpose instead of a triple destination, for example:
x % 2 == 0
Remember to specify your variables as well, so it is obvious that a line cannot be written separately. :-) It is usually used as an if . Hope this helps.
if
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 the complete function that will record the parity of your input on the console.
const checkNumber = (x) => { if(number%2 == 0){ //do something; console.log('number is Even'); }else{ //do otherwise; console.log('number is Odd'); } }
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array.each {| x | puts x if x% 2 == 0}
2 4 6 8 10