Check Prime Number in JavaScript

Beginner
⏱️ 11 min read
📚 Updated: May 2026
🎯 2 Code Examples
Number theory

What you’ll learn

  • A clear idea of prime versus composite, and why 1 is a special case.
  • How trial division works: try possible factors and stop early when you find one.
  • Two complete JavaScript programs: check one number (with a tight loop bound) and print primes between 1 and 20, plus a browser live preview.

Overview

You will answer one question: “Is this whole number n prime?” A prime has no divisor strictly between 1 and n. The code tries candidate divisors; if none work, n is prime. A second program reuses the same test to print small primes in a range.

Two programs

Example 1 checks a single value (here 17). Example 2 lists primes from 1 to 20.

Live preview

Type a number and see prime or not prime, with the first factor shown when it is not prime.

Interview-ready detail

Edge cases (n ≤ 1, 2), the square-root loop bound, and complexity in one place.

Prerequisites

You should be fine if you have written small JavaScript programs with loops and console.log.

  • Function declarations, for loops, and console.log.
  • for loops and the remainder operator % (read “n modulo i equals zero” as “i divides n evenly”).

What is a prime number?

A prime number is an integer greater than 1 whose only positive divisors are 1 and itself. If you can find any other integer between 1 and that number that divides it evenly, the number is not prime (it is composite).

Think of primes as building blocks: 12 = 2 × 2 × 3 uses primes 2 and 3. The number 17 cannot be split that way using smaller whole factors, so 17 is prime.

Prime two divisors: 1 and n
Composite extra divisors between 1 and n
Unit n = 1 (neither)

Why the square-root bound works

Suppose n > 1 is not prime. Then n = a × b where both a and b are integers greater than 1. One of them cannot be larger than √n without the product exceeding n. So some divisor (other than 1) appears in the range 2 through ⌊√n⌋.

Example: n = 15

We find 3 × 5 = 15. The factor 3 is less than or equal to √15 ≈ 3.87. The loop reaches 3 and proves 15 is not prime.

Quick examples

17 Prime
Check idea
No i from 2 to √17 divides 17.
18 Not prime
Factor
2 × 9, 3 × 6, …

Takeaway: one successful division is enough to say “not prime”; proving prime means no divisor up to √n.

Live preview

This uses the same trial idea as the C samples: try i while i · i ≤ n. For very large n the browser may slow down; this demo caps input size so the tab stays smooth.

  1. Enter a whole number (try 17, 1, or 18).
  2. Press Run check or Enter.
  3. Read whether it is prime; if not, you will see a small factor that proves it.

Use integers. For this page, |n| above 1012 is blocked so the preview stays responsive.

Live result
Press “Run check” to classify n.

Algorithm

Goal: return “prime” if n has no divisor strictly between 1 and n; otherwise return “not prime”.

Handle small values

If n ≤ 1, it is not prime by definition. Return false (or print a clear message).

Try candidate divisors

Let i run from 2 upward while i · i ≤ n (same as i ≤ n / i for positive n). If n % i == 0, you found a nontrivial factor—stop: not prime.

Finish

If the loop completes with no hit, n is prime.

📜 Pseudocode

Pseudocode
function isPrime(n):
    if n < 2:
        return false
    for i from 2 while i * i ≤ n:
        if n mod i = 0:
            return false
    return true
1

Check a single number (square-root loop)

Classic interview shape: reject n ≤ 1, then trial division with i ≤ n / i so we never multiply i by itself in a way that risks overflow on large int values.

JavaScript
function isPrime(n) {
  if (n <= 1) {
    return false;
  }
  for (let i = 2; i <= n / i; i++) {
    if (n % i === 0) {
      return false;
    }
  }
  return true;
}

const testNumber = 17;
if (isPrime(testNumber)) {
  console.log(testNumber + " is a prime number.");
} else {
  console.log(testNumber + " is not a prime number.");
}
Try it Yourself

Explanation

Walk through the function the way you would in an oral exam: guard, loop, early exit, default to prime.

if (n <= 1) return 0;

Definition first. Zero, one, and negatives are not prime in the usual textbook sense.

for (int i = 2; i <= n / i; ++i)

Tight bound. This is equivalent to i * i <= n but avoids computing i * i for big integers.

if (n % i == 0) return 0;

Found a factor. Then n has more than two divisors, so it cannot be prime.

return 1;

No factor up to √n. Therefore n is prime.

2

Prime numbers between 1 and 20

Same helper as many textbooks: loop i from 2 while i * i ≤ num. The outer loop prints every prime in the closed range [1, 20] (so 1 is skipped automatically).

JavaScript
function isPrime(num) {
  if (num <= 1) {
    return false;
  }
  for (let i = 2; i * i <= num; i++) {
    if (num % i === 0) {
      return false;
    }
  }
  return true;
}

function listPrimesInRange(start, end) {
  const values = [];
  for (let i = start; i <= end; i++) {
    if (isPrime(i)) {
      values.push(String(i));
    }
  }
  console.log("Prime numbers in the range " + start + " to " + end + ":");
  console.log(values.join(" "));
}

const start = 1;
const end = 20;
listPrimesInRange(start, end);
Try it Yourself

Explanation

list_primes_in_range is only a thin wrapper: it calls is_prime for each candidate and prints hits.

for (int i = start; i <= end; ++i)

Outer scan. Change start and end to match your assignment; keep them sensible so the program finishes quickly.

if (isPrime(i)) values.push(String(i));

Reuse the test. You do not rewrite the math—one function stays the single source of truth.

Optimization and style notes

Even check. After testing 2, you can step i by 2 to skip even candidates (handle 2 before the loop). Helpful when n is large and you want a constant-factor speedup.

Precomputed tables. If you need many primes up to a limit N, a sieve of Eratosthenes beats repeated trial division; this page sticks to the simple method for clarity.

Interview: state the definition, guard n < 2, then give trial division to √n with O(√n) time.

❓ FAQ

A prime is a whole number bigger than 1 that cannot be split into two smaller whole factors (except 1 times itself). Its only positive divisors are 1 and the number. Examples: 2, 3, 5, 7, 11.
No. By the usual definition, primes start at 2. The number 1 has only one positive divisor, so it is neither prime nor composite.
Yes. It is the smallest and the only even prime. Its divisors are exactly 1 and 2.
If n equals a times b and both a and b are bigger than the square root of n, then a times b would be bigger than n, which is impossible. So if n has a factor other than 1 and itself, at least one factor is no larger than the square root of n.
No, but it is the standard interview answer for modest sizes. Much faster tests exist for huge numbers; they are not required for typical classroom C demos.
Primality is defined for integers greater than 1. Negative inputs are usually rejected or treated as invalid in simple programs.

🔄 Input / output examples

For Example 1, change testNumber in the script. For interactive code, read from prompt (browser) or readline (Node.js).

Input nTypical line printed
1717 is a prime number.
1818 is not a prime number.
22 is a prime number.
11 is not a prime number.

For Example 2 with start = 1 and end = 20:

Console
Prime numbers in the range 1 to 20:
2 3 5 7 11 13 17 19

Edge cases and pitfalls

Most bugs come from the boundaries 0, 1, and 2, or from using a loop that never runs when it should.

n = 2

Smallest prime

The inner loop should not reject 2. With i starting at 2 and condition i ≤ n / i, the loop body does not run for n = 2, and the function correctly returns prime.

n = 1

Not prime

Returning “not prime” is correct; do not call 1 prime in your print message.

Squares

Perfect squares

9 is not prime because 3 × 3 = 9. The trial loop catches i = 3.

Overflow

i * i in JavaScript

For very large values, prefer i <= n / i or cap inputs in UI previews so the check remains responsive.

⏱️ Time and space complexity

MethodTime (single n)Extra space
Trial to n / 2O(n)O(1)
Trial to √n (i ≤ n/i)O(√n)O(1)
All k in [a, b] with √ test eachroughly O((b-a)√b)O(1)

Only a handful of integer variables are used, so extra memory stays constant aside from the normal call stack.

Summary

  • Definition: primes are integers n > 1 with no divisor strictly between 1 and n.
  • Code: trial division; stop at √n and return early when a factor appears.
  • Watch-outs: treat n ≤ 1 first, remember 2 is prime, and avoid i * i overflow on huge int values.
Did you know?

The only even prime is 2. Every integer greater than 1 is either prime or composite—except 1, which is neither. There are infinitely many primes (a classic proof attributed to Euclid).

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful