A prime number is a whole number greater than 1 that has no divisors other than 1 and itself — 2, 3, 5, 7, 11, 13... are all prime, while 4, 6, 8, 9 are not. This program checks whether a given number is prime by testing whether any smaller number divides it evenly.
Program to Check Prime Number in JavaScript
function isPrime(num) {
if (num < 2) return false;
// Only need to check divisors up to the square root of num
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false; // found a divisor, so it's not prime
}
}
return true;
}
console.log(isPrime(29));
console.log(isPrime(15));
Output:
true
false
The loop only checks divisors up to Math.sqrt(num) instead of all the way up to num — if a number greater than its square root divided it evenly, there would have to be a matching smaller divisor too, so checking beyond the square root is redundant. This keeps the function fast even for fairly large numbers.
Numbers less than 2 (0, 1, and negatives) are never prime, which is why the function returns false immediately for them, before the loop even has a chance to run — a common edge case this kind of check needs to handle explicitly.
Printing All Prime Numbers up to N
function printPrimesUpTo(n) {
const primes = [];
for (let num = 2; num <= n; num++) {
if (isPrime(num)) primes.push(num);
}
return primes;
}
console.log(printPrimesUpTo(30));
Output:
[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ]
