Explain Codes LogoExplain Codes Logo

How to determine if a number is odd in JavaScript

javascript
prompt-engineering
interview-preparation
best-practices
Nikita BarsukovbyNikita Barsukov·Jan 17, 2025
TLDR

In JavaScript, a number is determined to be odd using the modulus (%) operator. This operation yields true for odd numbers when it results in a remainder of 1 after being divided by 2.

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

Usage:

console.log(isOdd(5)); // true console.log(isOdd(8)); // false

Efficiency and alternatives

The modulus operator is the go-to approach. However, JavaScript also provides for an alternative solution using the bitwise AND (&) operator. This technique can be faster and equally reliable.

const isOdd = num => (num & 1) === 1; // "& 1" — secretly checking for oddness

Attention to details

Input validation is a crucial aspect of any function in JavaScript. Without it, the modulus operator may return unexpected results with non-integer numbers:

console.log(isOdd(4.5)); // false...wait, isn't 4.5 neither odd nor even?

For handling such edge cases, validate that the input is an integer:

const isOdd = num => Number.isInteger(num) && num % 2 !== 0; // Now we're talking

Performance matters

While the modulus operator is intuitive, efficiency considerations often lead to heated debates. Here’s a rapid comparison in a real-world context:

Modulus vs. Bitwise

function isOddModulus(num) { // The classic return num % 2 !== 0; } function isOddBitwise(num) { // The hipster return (num & 1) === 1; }

While the bitwise operation can be marginally faster, for the majority of applications, the difference is not significant.

Writing robust code

While building functions, it is of utmost importance that they handle a diverse range of data inputs and types, while maintaining robust performance:

function isOdd(num) { if (typeof num !== 'number' || !Number.isInteger(num)) { throw new Error('Input must be an integer'); // Throwing tantrums when the input isn't right } return (num & 1) === 1; }

This function not only checks for oddness but also validates the input.