Check if a number is odd or even in JavaScript

OpenJavaScript 0

Last updated: September 27, 2022.

There is no in-built function or method to check if a number is odd or even in JavaScript. We therefore have to create a function ourselves to perform this check.

This can be done with the help of the remainder operator (%).

Since an even number always has a remainder of zero, if applying the remainder operator to a number returns this outcome, the number must be even. Conversely, if a remainder exists, the number must be odd.

Below is a function that perform this check, including a pre-check for whether the number passed into it when it is called is an integer. The function is then called three times:

function oddOrEven(x) {
    // First, check if number is integer. If not,
    // keyword return stops function processing
    // and a console error is created
    if (!Number.isInteger(x)) {
        return console.error("Not an integer!")
    }
    // Checks the remainder of the number passed 
    // into the function if divided by 2. If it 
    // is 0, the if statement is executed, if it
    // is not, the else statement runs.
    if (x % 2 === 0) {
        console.log("The number is even");
    } else {
        console.log("The number is odd");
    }
}

oddOrEven(2) // The number is even 
oddOrEven(3) // The number is odd
oddOrEven(0.2) // Not an integer

Alternative solution using the ternary operator

The odd or even number check function can also be written using the ternary operator. The syntax is as follows: statement : returnIfTrue : returnIfFalse.

Note that because a ternary statement requires a returnIfFalse expression, it is only applied to the check of whether a number is even or odd:

function oddOrEven(x) {
    if (!Number.isInteger(x)) { return console.error("Not an integer") }
    x % 2 === 0 ? console.log("The number is even") : console.log("The number is odd")
}

oddOrEven(2) // The number is even 
oddOrEven(3) // The number is odd
oddOrEven(0.2) // Not an integer