Check a prime number in JavaScript
Test divisors up to the square root of the number. Press Run to try it, then change the code and run it again.
main.js
function isPrime(n) {
if (n < 2) return false;
for (let i = 2; i * i <= n; i++) {
if (n % i === 0) return false;
}
return true;
}
const n = Number(prompt("Enter a number:"));
console.log(`${n} is ${isPrime(n) ? "" : "not "}a prime number`);
Output
Press Run to see the output.
More JavaScript examples
- Hello, World · Print a line of text to the console.
- Reverse a string · Split a string into characters, reverse them and join them back.
- Fibonacci series · Print the first n Fibonacci numbers.
- Promises with async/await · Wait for a timer with await, the way you would wait for a network request.
- map, filter and reduce · Transform, filter and total an array of objects.