JavaScript Program to Check if Number is Even or Odd
Use the modulus operator
% in JavaScript to check if a number is even or odd: if number % 2 === 0, it is even; otherwise, it is odd.Examples
Input4
Output4 is even
Input7
Output7 is odd
Input0
Output0 is even
How to Think About It
To check if a number is even or odd, divide it by 2 and look at the remainder. If the remainder is 0, the number is even because it divides evenly by 2. If the remainder is 1, the number is odd because it leaves a leftover when divided by 2.
Algorithm
1
Get the input number.2
Calculate the remainder when the number is divided by 2.3
If the remainder is 0, the number is even.4
Otherwise, the number is odd.5
Print the result.Code
javascript
const number = 7; if (number % 2 === 0) { console.log(`${number} is even`); } else { console.log(`${number} is odd`); }
Output
7 is odd
Dry Run
Let's trace the number 7 through the code to see how it determines if it's even or odd.
1
Input number
number = 7
2
Calculate remainder
7 % 2 = 1
3
Check remainder
Since remainder is 1, number is odd
4
Print result
"7 is odd" is printed
| Number | Number % 2 | Even or Odd |
|---|---|---|
| 7 | 1 | Odd |
Why This Works
Step 1: Using modulus operator
The % operator gives the remainder of division, which helps us find if a number divides evenly by 2.
Step 2: Checking remainder
If the remainder is 0, the number is even because it divides exactly by 2.
Step 3: Determining odd
If the remainder is not 0 (usually 1), the number is odd because it leaves a leftover when divided by 2.
Alternative Approaches
Using bitwise AND operator
javascript
const number = 7; if ((number & 1) === 0) { console.log(`${number} is even`); } else { console.log(`${number} is odd`); }
This method uses bitwise operation to check the last binary digit; it's very fast but less readable for beginners.
Using ternary operator
javascript
const number = 7; console.log(`${number} is ${number % 2 === 0 ? 'even' : 'odd'}`);
This is a concise way to write the check and print in one line, improving readability.
Complexity: O(1) time, O(1) space
Time Complexity
The operation uses a single modulus calculation which takes constant time regardless of input size.
Space Complexity
No extra memory is needed beyond the input and a few variables, so space is constant.
Which Approach is Fastest?
Both modulus and bitwise AND methods run in constant time; bitwise may be slightly faster but less clear.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Modulus operator (%) | O(1) | O(1) | Clarity and simplicity |
| Bitwise AND (&) | O(1) | O(1) | Performance in low-level code |
| Ternary operator | O(1) | O(1) | Concise code style |
Use the modulus operator
% to quickly check if a number is even or odd.Beginners often forget to use
=== for comparison and use = which assigns instead of compares.