How to check if a number is even
Short answer
An even number leaves a remainder of zero when divided by 2:
console.log(10 % 2 === 0);Output:
trueA reusable function
It is convenient to move the check into a function with a clear name:
const isEven = (number) => number % 2 === 0;
console.log(isEven(7));
console.log(isEven(0));Output:
false
trueDivisibility by another number
The same technique checks divisibility by any other number:
console.log(15 % 5 === 0);
console.log(16 % 5 === 0);Output:
true
falseOdd numbers
For odd numbers compare the remainder with zero too, but with !==:
const isOdd = (number) => number % 2 !== 0;
console.log(isOdd(7), isOdd(-7), isOdd(8));Output:
true true falseCommon mistake
For negative numbers the remainder is negative, so the check % 2 === 1 misses odd negative numbers:
console.log(-7 % 2);
console.log(-7 % 2 === 1);Output:
-1
falseFunctions used in this recipe
- Math.abs — Returns the absolute value of a number — its value without the sign.