Run

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

Open the full JavaScript online compiler →