How to check if a number is even in JavaScript
Checking if numbers are even is fundamental for alternating patterns, conditional logic, data grouping, and implementing features like zebra striping or alternating layouts in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented even number checking extensively in components like table row styling, pagination logic, and layout systems where alternating behaviors enhance visual organization and user experience. From my extensive expertise, the most efficient and mathematically sound approach is using the modulo operator (%) to test divisibility by 2. This method is simple, performant, and directly expresses the mathematical definition of even numbers.
Use the modulo operator (%) to check if a number is divisible by 2.
const number = 4
const isEven = number % 2 === 0
// Result: true
const checkEven = (num) => num % 2 === 0
// Usage: checkEven(6) returns true, checkEven(7) returns false
The modulo operator %
returns the remainder after division. When a number is divided by 2, even numbers have no remainder (0), while odd numbers have a remainder of 1. In this example, 4 % 2
equals 0
, so 4 % 2 === 0
returns true
. The comparison === 0
ensures we get a boolean result. This works for all integers, including negative numbers: -4 % 2 === 0
is also true
. The function version provides a reusable way to check any number.
Best Practice Note:
This is the same approach we use in CoreUI components for implementing alternating row colors, conditional styling, and pattern-based layouts across our component library.
For performance-critical applications, you can use bitwise AND: (number & 1) === 0
, which checks the least significant bit. However, the modulo approach is more readable and sufficient for most use cases. Always ensure you’re working with integers when checking for even/odd properties.