Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a number is odd in JavaScript

Tags:

javascript

People also ask

How do you check if a number is odd?

If a number divided by 2 leaves a remainder of 1, then the number is odd. You can check for this using num % 2 == 1 .

Is 0 even or odd In JavaScript?

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.

How do you check if a number is even or odd in jquery?

The :even selector selects each element with an even index number (like: 0, 2, 4, etc.). The index numbers start at 0. This is mostly used together with another selector to select every even indexed element in a group (like in the example above). Tip: Use the :odd selector to select elements with odd index numbers.


Use the below code:

function isOdd(num) { return num % 2;}
console.log("1 is " + isOdd(1));
console.log("2 is " + isOdd(2));
console.log("3 is " + isOdd(3));
console.log("4 is " + isOdd(4));

1 represents an odd number, while 0 represents an even number.


Use the bitwise AND operator.

function oddOrEven(x) {
  return ( x & 1 ) ? "odd" : "even";
}

function checkNumber(argNumber) {
  document.getElementById("result").innerHTML = "Number " + argNumber + " is " + oddOrEven(argNumber);
}
 
checkNumber(17);
<div id="result" style="font-size:150%;text-shadow: 1px 1px 2px #CE5937;" ></div>

If you don't want a string return value, but rather a boolean one, use this:

var isOdd = function(x) { return x & 1; };
var isEven  = function(x) { return !( x & 1 ); };

You could do something like this:

function isEven(value){
    if (value%2 == 0)
        return true;
    else
        return false;
}

function isEven(x) { return (x%2)==0; }
function isOdd(x) { return !isEven(x); }

Do I have to make an array really large that has a lot of even numbers

No. Use modulus (%). It gives you the remainder of the two numbers you are dividing.

Ex. 2 % 2 = 0 because 2/2 = 1 with 0 remainder.

Ex2. 3 % 2 = 1 because 3/2 = 1 with 1 remainder.

Ex3. -7 % 2 = -1 because -7/2 = -3 with -1 remainder.

This means if you mod any number x by 2, you get either 0 or 1 or -1. 0 would mean it's even. Anything else would mean it's odd.


This can be solved with a small snippet of code:

function isEven(value) {
    return !(value % 2)
}

Hope this helps :)


In ES6:

const isOdd = num => num % 2 == 1;