A prime number is an integer greater than 1 that has exactly two positive divisors: 1 and itself.
Remember
Prime: 2, 3, 5, 7, 11, 13, 17, 19, ...
Not prime: 1 (neither), 4, 6, 8, 9, 10, 12, ...
Rule:
n > 1 and no divisor in 2 .. floor(√n)
n
Divisors
Prime?
7
1, 7
Yes
9
1, 3, 9
No
2
1, 2
Yes (only even prime)
1
1
No
Approach
How to Check a Prime Number in JavaScript
Four clear steps — then reuse the helper to list primes in a range.
If n ≤ 1, return false.
If n is 2 or 3, return true (optional fast path).
Try divisors from 2 to √n; if any divides n, it is not prime.
If no divisor is found, n is prime.
Method
Idea
Time
Best for
Trial to √n
No divisor in 2..√n
O(√n)
Single check (default)
Skip even divisors
Handle 2, then odd i only
O(√n)
Slightly faster checks
Range scan
Call isPrime for each value
O(N√N)
Listing primes 1..N
Pseudocode
Pseudocode
function IsPrime(n):
if n <= 1: return false
i = 2
while i * i <= n:
if n % i == 0:
return false
i = i + 1
return true
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Definition
n > 1 with only divisors 1 and n
1
Neither prime nor composite
2
Smallest and only even prime
Loop bound
i * i <= n (same as i <= √n)
Composite
Has a factor ≤ √n
Classic checks
7 yes; 9 no; 1 no
Try it
Live Preview
Enter an integer to see trial division up to √n and the prime verdict.
Whole numbers only. Tap a chip or type a value.
Result
n = 17
Check divisors from 2 to floor(√17)=4
No divisor found
17 is prime
Code
JavaScript Programs
Start with a reusable isPrime helper, list primes in a range, then skip even divisors for a small speedup. Each example has a Try it Yourself editor.
Example 1 — isPrime Check
Return true only when no divisor exists from 2 through √n.
JavaScript
function isPrime(n) {
if (n <= 1) {
return false;
}
for (let i = 2; i * i <= n; i++) {
if (n % i === 0) {
return false;
}
}
return true;
}
const number = 17;
if (isPrime(number)) {
console.log(number + " is prime");
} else {
console.log(number + " is not prime");
}
The loop runs while i * i <= n, which means i ≤ √n.
If any i divides n, a third divisor exists → not prime.
If the loop finishes with no hit, only divisors are 1 and n.
For 17, checks stop at 4 and none divide, so the answer is true.
Example 2 — Primes in a Range
Reuse isPrime to print every prime from 1 to 20.
JavaScript
function isPrime(n) {
if (n <= 1) {
return false;
}
for (let i = 2; i * i <= n; i++) {
if (n % i === 0) {
return false;
}
}
return true;
}
const start = 1;
const end = 20;
console.log("Primes from " + start + " to " + end + ":");
let line = "";
for (let i = start; i <= end; i++) {
if (isPrime(i)) {
line += i + " ";
}
}
console.log(line.trim());