How to Check if a Number is Odd in JavaScript

  John Mwaniki /    Updated on 07 Jul 2024

In this article, you will learn different methods to check if a number is odd in JavaScript, with the help of clear examples for better understanding.

Odd numbers are integers that cannot be evenly divided by 2, leaving a remainder of 1. This property serves as the foundation for various methods to check for oddness in JavaScript.

Methods to Check if a Number is Odd JavaScript

There are multiple ways in which one can use to check if a number is odd. Below we cover some of them:

1. Using the Modulo Operator (%)

The most straightforward way to check if a number is odd is by using the modulo operator (%).

This operator divides one integer number by another and returns the remainder.

When a number is divided by 2 and the remainder is 0, it signifies an even number. Any non-zero remainder, on the other hand, reveals the number is odd.

Example 1

var number = 7;
if (number % 2 !== 0) {
    console.log("The number is odd");
}
else {
    console.log("The number is even");
}

Output:
The number is odd

In this example, we have divided the number we want to test (7) by 2 using the modulo operator and then compared the remainder with zero (0) using the 'not identical' operator. If the remainder is not equal to 0, we know it is odd and log a message ('The number is odd') in the console. Else, we log a message ('The number is even').

Example 2

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

// Example usage
console.log(isOdd(5)); // Output: true
console.log(isOdd(10)); // Output: false

In this example, the function isOdd() checks if the remainder of dividing the input number by 2 is not equal to 0, indicating that the number is odd.

2. Bitwise AND Operation

Every number can be represented in binary format. The binary representation of odd numbers always ends with 1.

We can use the bitwise AND operator (&) with 1 to reveal whether a number is odd.

function isOddBitwise(number) {
  return (number & 1) === 1;
}

// Example usage
console.log(isOddBitwise(7)); // Output: true
console.log(isOddBitwise(6)); // Output: false

In this example, the isOddBitwise() function checks if the result of the bitwise AND operation between the input number and 1 is equal to 1.

3. Using Math.floor and Division

An alternative method involves using Math.floor in combination with division. You obtain the integer part by dividing the number by 2 and rounding down the result. This can then be compared with the division result without rounding down.

If the two are not equal, there is a remainder and the number is odd. Otherwise, it means that the number is even.

Example

let number = 6;
if (Math.floor(number / 2) !== number / 2) {
    console.log("The number is odd");
}
else{
    console.log("The number is even");
}

Output:
The number is even

That's it!

Now you know several ways to check if a number is odd or even in JavaScript.