How to Calculate if a Number is Odd or Even in JavaScript
Learn how to determine whether or not a number is odd or even in JavaScript.
I don't know how or why it took me so long to need this, but I only recently discovered the need to determine whether or not a number was even or odd. It uses the less-common remainder operator %
.
Since all even numbers are divisible by 2 with no remainder, you can test whether a number is even with the following, where n
is the number you'd like to test:
const isEven = (n) => (n % 2 === 0) ? true : false;
console.log( isEven(8) ) // output: true
console.log( isEven(9) ) // output: false
CodePen Example
Check out the CodePen below for more information and review the MDN docs here.