isEven and isOdd with bitwise AND in JavaScript
Beginner · 4 min read
Even or odd is one of the first checks every programmer writes. You use it to stripe table rows, to split a list into two columns, or to alternate the side of a timeline. It looks too simple to get wrong, yet the most common version fails for every negative odd number.
In this tutorial you will write isEven and isOdd that are right for negative numbers and refuse fractions, since a number like 8.5 is neither even nor odd. Then you will look at a popular shortcut, n & 1, and see what it does with 8.5. You need to know %, the remainder operator, and Number.isInteger.
Parity, in plain words
Parity is the name for "even or odd". A whole number is even when it divides by 2 with nothing left over, and odd when 1 is left over. Zero is even. Negative numbers have parity too: -4 is even and -7 is odd.
Fractions don't have parity at all. 8.5 isn't even and it isn't odd. A good helper should say false to both questions.
What & does
& is the bitwise AND operator. It works on the binary digits (bits) of a number. n & 1 keeps only the last bit, which is 1 for odd numbers and 0 for even ones. Before it looks, & turns its input into a 32-bit whole number, cutting off any fraction. That detail matters in Step 5.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
26 Even and odd
easyWrite isEven and isOdd that are right for negatives and refuse a fraction. Then show what n & 1 does with 8.5.
Stuck? Three hints, smallest first
- 1.
n % 2 === 0is safe for even; the odd case needs care because-7 % 2is-1. - 2. Insist on
Number.isIntegerfirst, or 8.5 will be classified. - 3.
&converts to a 32-bit integer first, which truncates the fraction before it looks.
Step 1: isEven with %
const isEvenTry = (n) => n % 2 === 0;
console.log(isEvenTry(8), isEvenTry(7)); // true false
console.log(isEvenTry(-4), isEvenTry(0)); // true true
This is already right for negatives, because -4 % 2 is -0, and -0 === 0 is true.
Step 2: the isOdd wrong turn
The natural odd test is "the remainder is 1":
const isOddTry = (n) => n % 2 === 1;
console.log(isOddTry(7)); // true
console.log(isOddTry(-7)); // false, but -7 is odd
console.log(-7 % 2); // -1
% keeps the sign of the number on the left, so -7 % 2 is -1, not 1. Every negative odd number fails this test.
Step 3: fix it with Math.abs
Math.abs gives the absolute value, the number without its minus sign. Taking it before comparing turns -1 into 1:
const isOddAbs = (n) => Math.abs(n % 2) === 1;
console.log(isOddAbs(-7), isOddAbs(7), isOddAbs(8)); // true true false
Another fix is n % 2 !== 0. Both work for whole numbers.
Step 4: refuse fractions
Only whole numbers have parity, so say that in the code. Number.isInteger(n) is true for whole numbers and false for anything else, including 8.5, NaN and Infinity. Put it first, joined with &&:
const isEven = (n) => Number.isInteger(n) && n % 2 === 0;
const isOdd = (n) => Number.isInteger(n) && Math.abs(n % 2) === 1;
console.log(isEven(8.5), isOdd(8.5)); // false false
console.log(isEven(0), isOdd(-7)); // true true
&& stops as soon as the left side is false, so a fraction never reaches the parity check. The guard makes the rule clear to anyone reading: these functions only answer for whole numbers.
Step 5: the bitwise shortcut
n & 1 is a well-known fast idiom. Compare it on 8 and on 8.5:
console.log(8 & 1); // 0: even
console.log(7 & 1); // 1: odd
console.log(8.5 & 1); // 0: 8.5 was cut to 8 first, so it looks even
For whole numbers it agrees with %. But it accepts 8.5 without complaint and calls it even. That is why the answer uses % with an explicit Number.isInteger guard.
Step 6: big numbers and the shortcut
& only keeps 32 bits, so a number like 2 to the 40th is cut down before the test. Parity still comes out right:
console.log((2 ** 40 + 1) & 1); // 1: odd, and correct
The bits that get cut off all stand for even amounts (2 to the 32nd and up), so dropping them never changes the last bit. Good to know, but it is one more rule to remember, and % doesn't need it.
Step 7: use it on a list
Because isEven takes one argument, you can pass it straight to array methods:
console.log([1, 2, 3, 4].map(isEven)); // [ false, true, false, true ]
console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].filter(isEven).length); // 5
The full solution
The answer panel defines both helpers, prints them on 8, 7, -7, 0 and 8.5, compares the bitwise test, and maps a short list. The checks underneath confirm each case, including that 8.5 & 1 reports even while isEven(8.5) is false. Press Run to see the output.
const isEven = (n) => Number.isInteger(n) && n % 2 === 0;
const isOdd = (n) => Number.isInteger(n) && Math.abs(n % 2) === 1;
console.log('8, 7 :', isEven(8), isEven(7));
console.log('-7 odd? :', isOdd(-7), 'because -7 % 2 is', -7 % 2);
console.log('0 even? :', isEven(0));
console.log('8.5 :', isEven(8.5), isOdd(8.5), '<- neither');
console.log('8.5 & 1 :', 8.5 & 1, '<- truncated to 8 first, so it looks even');
console.log('big integer :', (2 ** 40 + 1) & 1, '<- parity survives 32-bit truncation');
console.log('1 to 4 :', [1, 2, 3, 4].map(isEven));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('8 is even and 7 is not', [isEven(8), isEven(7)], [true, false]);
test('-7 is odd, which is why abs is needed', isOdd(-7), true);
test('since -7 % 2 is -1, not 1', -7 % 2, -1);
test('zero is even', isEven(0), true);
test('a fraction is neither even nor odd', [isEven(8.5), isOdd(8.5)], [false, false]);
test('though the bitwise test calls 8.5 even, having truncated it', (8.5 & 1) === 0, true);
test('& 1 does agree on integers, even large ones, because 2 ** 32 is even', (2 ** 40 + 1) & 1, 1);
test('parity alternates down a list', [1, 2, 3, 4].map(isEven), [false, true, false, true]);
test('and exactly half of 1 to 10 are even', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].filter(isEven).length, 5);
n % 2 === 1 is the bug to remember: it is false for every negative odd number, because the remainder carries the dividend's sign. Either compare against 0 with !==, or take the absolute value as isOdd does here.
n & 1 is the fast idiom and it is not equivalent. It runs ToInt32 on its operand, so 8.5 becomes 8 and reports even, and anything past 231 wraps. Parity happens to survive the wrap — 232 is even, so the low bit is preserved — but & silently accepting a fraction is the reason the explicit Number.isInteger guard is here.
Common mistakes
- Writing
n % 2 === 1for odd. It isfalsefor every negative odd number. UseMath.abs(n % 2) === 1orn % 2 !== 0. - Trusting
n & 1with any input. It cuts fractions first, so 8.5 looks even. - Forgetting zero. Zero is even.
isEven(0)must betrue.
Try it yourself
- Split
[3, -2, 7, 0, -9, 12]into two lists, evens and odds, withfilter. - Predict
isOdd(Infinity)andisEven(NaN), then run them. - Use
isEvenon the row index to give every second row in a list a different label.