Determining whether a number is odd or even is a fundamental programming task. In JavaScript, there are several ways to accomplish this. This tutorial will walk you through two simple methods - using the modulus operator and leveraging the bitwise AND operator.
The modulus operator (%) is the most common and straightforward way to determine if a number is odd or even. This operator returns the remainder of a division operation.
Key concept:
Code example:
function isEven(number) { return number % 2 === 0; } function isOdd(number) { return number % 2 !== 0; } // Usage: console.log(isEven(4)); // true console.log(isOdd(4)); // false console.log(isEven(7)); // false console.log(isOdd(7)); // true
Output:
The bitwise AND operator (&) can also be used to determine odd or even numbers. This approach relies on binary representation:
Key concept:
How it works:
Performing number & 1 checks the last bit of the number:
Code example:
function isEven(number) { return (number & 1) === 0; } function isOdd(number) { return (number & 1) === 1; } // Usage: console.log(isEven(4)); // true console.log(isOdd(4)); // false console.log(isEven(7)); // false console.log(isOdd(7)); // true
Output:
Feature | Modulus Operator % | Bitwise AND Operator & |
---|---|---|
Readability | Very easy to understand | Less intuitive |
Readability | Slightly slower for large numbers | Slightly faster for large numbers |
Use Case | General-purpose applications | Optimised low-level operations |
Both methods are effective for checking if a number is odd or even in JavaScript. Choose the one that best fits your specific use case. Happy coding! ?
The above is the detailed content of Coding challenge | How to check if a number is odd or even using JS. For more information, please follow other related articles on the PHP Chinese website!