Explain Codes LogoExplain Codes Logo

Testing whether a value is odd or even

javascript
input-validation
exception-handling
performance-optimization
Nikita BarsukovbyNikita BarsukovยทMar 8, 2025
โšกTLDR

Checking if a number is even or odd can be simply done with the modulus operator %. For even numbers, the operation number % 2 equals 0. Here's the core code:

const isEven = number => number % 2 === 0; // Usage: isEven(2); // true, because 2 loves to pair up! ๐Ÿ’ƒ๐Ÿ’ƒ isEven(3); // false, 3 is that friend who likes being the third wheel ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ฆ

Input validation and exception handling

In a practical coding scenario, you will need to validate the input first. This guard check will ensure the input is a finite number:

const isValidNumber = n => Number.isFinite(parseFloat(n)); const isEven = n => isValidNumber(n) && n % 2 === 0; // Paranoid mode on! ๐Ÿ‘€

Notice negative numbers are implicitly handled. However, using absolute values can make this more obvious:

const isOdd = n => isValidNumber(n) && Math.abs(n) % 2 === 1; // -3 says, "I might be negative, but I can still dance solo!" ๐Ÿ’ƒ

Tackling string inputs

Not all numbers come nicely packed as numbers. Sometimes they sneak in as strings ๐Ÿ•ต๏ธโ€โ™€๏ธ. Trim the whitespaces and transform the strings into numbers to uphold justice:

const isEvenString = str => { const number = Number(str.trim()); // Like a stealthy ninja in the night, we remove rogue spaces. return Number.isInteger(number) && number % 2 === 0; };

Enhancing performance

In performance-critical applications, using the bitwise AND operator & provides a super speedy even check:

const isEvenBitwise = n => (n & 1) === 0; // Some say this is the Flash of even-odd checks. โšก

Remember, JavaScript bitwise operations work on 32-bit integers. Very large numbers or non-integer values may introduce mind-bendy results.

Regular expressions to the rescue

When squaring off against strings representing numbers, regular expressions (regex) are your mighty sword and shield:

const isEvenRegex = str => /^-?\d*[02468]$/.test(str); const isOddRegex = str => /^-?\d*[13579]$/.test(str); // Strings may lie, but regex always speaks the truth. ๐Ÿ•ต๏ธโ€โ™‚๏ธ

This regex cut handles negative and positive integers like a seasoned samurai.

Special number cases

Infinity keeps claiming it's a number, but it doesn't act like one. It's a special case, as are other type coercion quirks. A fighter must be prepared:

isEven(Infinity); // false, because Infinity can't decide if it's even or odd, just like it can't decide its size! ๐Ÿค”

For robustness, handle such cases effectively:

const isEven = n => n !== Infinity && n !== -Infinity && n % 2 === 0;

Cross-browser compatibility

Every browser has its quirks, and respects JavaScript in its own unique way. To ensure that your function plays nice with everyone, test across different browsers. Unexpected issues can pop up, especially when using the latest ECMAScript magic.