Basics · beginner
JavaScript Program to Check if a Number is Even or Odd
Check whether a number is even or odd in JavaScript with the remainder operator (%), and learn why -3 % 2 is -1 and how to handle it safely.
- remainder operator %
- if/else
- for...of loop
- ternary operator
A whole number is even when dividing it by 2 leaves no remainder. JavaScript's % operator returns that remainder, so n % 2 === 0 means even.
Unlike Python, the result of % in JavaScript takes the sign of the left operand, so -3 % 2 is -1, not 1. Testing for === 0 avoids the problem.
The program
for (const n of [7, 12, 0, -3]) {
if (n % 2 === 0) {
console.log(n, "is even");
} else {
console.log(n, "is odd");
}
}
console.log("-3 % 2 is", -3 % 2);7 is odd
12 is even
0 is even
-3 is odd
-3 % 2 is -1How it works
- for...of gives n each value of the array in turn.
- n % 2 is the remainder after dividing by 2: 7 % 2 is 1 and 12 % 2 is 0.
- A remainder of 0 means the number is even; anything else means odd.
- The last line shows that -3 % 2 is -1 in JavaScript, which is why the program checks === 0 instead of === 1.
Watch it run line by line
Step through the loop and watch n change. The highlighted line jumps to either the "even" or the "odd" console.log, never both.
“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: With the ternary operator
The conditional (ternary) operator picks one of two values, which is handy inside a template literal. Bitwise n & 1 also works for whole numbers, including negative ones.
const n = 15;
console.log(`${n} is ${n % 2 === 0 ? "even" : "odd"}`);
console.log((-3 & 1) === 1 ? "odd" : "even");15 is odd
oddCommon mistakes
- Testing n % 2 === 1 for odd numbers, which is false for negative odd numbers because -3 % 2 is -1.
- Using = instead of === in the condition: if (n % 2 = 0) is a syntax error.
- Passing a decimal such as 2.5: 2.5 % 2 is 0.5, so it is reported as odd. Check Number.isInteger(n) first.
Try it yourself
- Split an array into evens and odds with filter().
- Print the even numbers from 1 to 20 with a for loop that steps by 2.
Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.