How to check if a number is odd or even (parity)

Darren Jones
February 23, 2022

The remainder operator (%) can be used to find the remainder of a when one number is divided by another. For example 13 % 5 returns 3 because the remainder when you divide 13 by 5 is 3.

We can use this to find the parity of a number by using the fact that if you divide any number by 2, even numbers will leave no remainder and odd numbers always have a remainder of 1.

copy code
javascript
const parity = number => number % 2 === 0 ?even:odd

parity(7)
// Output: 'odd'

parity(12)
// Output: 'even'

This function uses the ternary operator to return the string ‘even’ if the remainder is zero and ‘odd’ in all other cases (the only other case being the remainder is 1).


Related links

Know a better answer? Join our our community and let us know.