Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

true

A 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
true

Divisibility by another number

The same technique checks divisibility by any other number:

console.log(15 % 5 === 0);
console.log(16 % 5 === 0);

Output:

true
false

Odd 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 false

Common 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
false

Functions used in this recipe

  • Math.abs — Returns the absolute value of a number — its value without the sign.

Thanks for reading!

Donate to the site — we work hard for you.