Skip to content
Devtoolry

Numbers · intermediate

JavaScript Program to Print Prime Numbers in a Range

Print all prime numbers between two numbers in JavaScript with a labelled nested loop, then with the much faster Sieve of Eratosthenes using a typed array.

Printing the primes between two numbers combines a loop over the candidates with an inner loop that looks for divisors. JavaScript has no for-else like Python, but a labelled continue jumps straight to the next candidate as soon as a divisor is found.

The program

JavaScript
const low = 10, high = 50;
const primes = [];

candidates: for (let n = Math.max(low, 2); n <= high; n++) {
  for (let d = 2; d * d <= n; d++) {
    if (n % d === 0) continue candidates;
  }
  primes.push(n);
}

console.log(primes.join(" "));
Output
11 13 17 19 23 29 31 37 41 43 47

How it works

  1. The outer loop, labelled candidates, visits every number from low to high, starting at 2 at the earliest.
  2. The inner loop tries divisors up to the square root of n.
  3. continue candidates skips the rest of both loops for this n and moves on to the next candidate.
  4. Only numbers whose inner loop finishes without a divisor reach primes.push(n).

Watch it run line by line

Watch n = 15: the inner loop tries d = 2 and d = 3, then the highlighted line jumps straight back to the outer for. For n = 11 the inner loop ends normally and primes gains 11.

“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.

Another way: Sieve of Eratosthenes

For large ranges, cross out multiples instead of testing every number. A Uint8Array of flags is compact and fast; the sieve finds all primes below a million in a few milliseconds in a modern browser.

JavaScript
function primesUpTo(limit) {
  const composite = new Uint8Array(limit + 1);
  const result = [];
  for (let p = 2; p <= limit; p++) {
    if (composite[p]) continue;
    result.push(p);
    for (let m = p * p; m <= limit; m += p) composite[m] = 1;
  }
  return result;
}

console.log(primesUpTo(50).filter((p) => p >= 10).join(" "));
console.log(primesUpTo(1000000).length);
Output
11 13 17 19 23 29 31 37 41 43 47
78498

Common mistakes

  • Using a plain continue inside the inner loop: it only skips to the next divisor, so non-primes are still pushed.
  • Writing n < high, which leaves out high itself.
  • Starting the sieve's inner loop at 2 * p instead of p * p: correct, but it repeats work smaller primes have already done.

Try it yourself

  • Print how many primes there are below 1,000 (168).
  • Find twin primes such as (11, 13) that differ by 2.

Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.