Prime numbers have exactly two positive factors: 1 and the number itself. The first five primes are 2, 3, 5, 7, and 11.
Enter a limit to display all primes from 2 through that value, inclusive. The original page said “up to” while its loop stopped before the input value; the updated demo makes the behavior match the heading.
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>JavaScript Prime Numbers up to a Limit</title></head>
<body>
<label for="t1">Show prime numbers up to</label>
<div class="col-sm-4 px-0"><input type="number" class="form-control" id="t1" min="2" max="100000" step="1"></div>
<button type="button" class="btn btn-primary btn-sm mt-2" id="b1">Submit</button>
<div id="d1" class="alert alert-success mt-3" style="word-break:break-word" aria-live="polite">Output here</div>
<script>
const input = document.getElementById("t1");
const output = document.getElementById("d1");
const submitButton = document.getElementById("b1");
function isPrime(number) {
if (number < 2) return false;
if (number === 2) return true;
if (number % 2 === 0) return false;
for (let divisor = 3; divisor <= Math.sqrt(number); divisor += 2) {
if (number % divisor === 0) return false;
}
return true;
}
function showPrimes() {
const limit = Number(input.value.trim());
if (!Number.isInteger(limit) || limit < 2 || limit > 100000) {
output.textContent = "Enter an integer from 2 to 100,000.";
return;
}
const primes = [];
for (let number = 2; number <= limit; number += 1) {
if (isPrime(number)) primes.push(number);
}
output.textContent = `Prime numbers up to ${limit}: ${primes.join(", ")}`;
}
submitButton.addEventListener("click", showPrimes);
</script>
</body>
</html>
Each candidate number is checked by the reusable isPrime() function. Even values greater than 2 are rejected immediately, and odd divisors are tested only through the candidate's square root.
| Number.isInteger() | Check whether a parsed value is an integer. |
| parseInt() | Convert a string to an integer where that conversion is appropriate. |
Next lower value of any decimal number JavaScript Basic JavaScript variable
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.