How to check if a number is prime in JavaScript
Checking if a number is prime is essential for cryptographic algorithms, mathematical computations, number theory applications, and implementing features like prime factorization or security protocols in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented prime number checking in components like mathematical validators, algorithm demonstrations, and educational tools where efficient prime detection is crucial for performance and accuracy. From my extensive expertise, the most efficient approach is testing divisibility only up to the square root of the number, significantly reducing computational complexity. This optimization is based on the mathematical principle that if a number has a divisor greater than its square root, it must also have a corresponding divisor smaller than the square root.
Test divisibility up to the square root of the number for efficient prime checking.
const isPrime = (num) => {
if (num < 2) return false
if (num === 2) return true
if (num % 2 === 0) return false
for (let i = 3; i <= Math.sqrt(num); i += 2) {
if (num % i === 0) return false
}
return true
}
// Usage: isPrime(17) returns true, isPrime(15) returns false
The function first handles edge cases: numbers less than 2 are not prime, 2 is the only even prime number, and other even numbers are not prime. The loop starts at 3 and checks only odd divisors up to the square root of the number using Math.sqrt(num)
. If any divisor is found, the number is not prime. The i += 2
increment skips even numbers since we already know they can’t be divisors of odd numbers. This algorithm has O(√n) time complexity, making it efficient for large numbers compared to checking all numbers up to n-1.
Best Practice Note:
This is the same approach we use in CoreUI components for mathematical validations, algorithm demonstrations, and computational utilities across our component library. For very large numbers, consider using probabilistic primality tests like Miller-Rabin. Cache results for frequently checked numbers to improve performance. The function handles all positive integers correctly and returns boolean values consistently. This implementation balances efficiency with readability for most JavaScript applications requiring prime number validation.