JavaScript Program to identify Prime Number

The blog provides the step by step solution for writing JavaScript program to find the Prime Number from the given number.  The user should have knowledge on below topics Control Statements in JavaScript

What is a prime number ?

The prime number is the number which is only divisible by 1 or itself. Example : 2,3,5,7,11

Steps to write Prime Number Program
  • Prompt user to enter the number
  • Create temporary variable isNumberPrime = true;
  • Check if the enter number is equal to 1 or less than 1 , then display “1 cannot be Prime Number”
  • Check if Number is greater than 1, then iterate each number till it reaches to the given Number
  • If Number divided with iteration Value =0, then display “Number cannot be Prime Number”
  • else display ” Number is Prime Number”
let userValue = parseInt(prompt("Enter the number: "));
let isNumberPrime  = true;

if (userValue == 1) {
    document.writeln("1 is neither prime nor composite number.");
else if (userValue < 1) {
   document.writeln("Negative number cannot be a prime number");
else if (userValue > 1) {
    for (let i = 2; i < userValue; i++) {
        if (userValue % i == 0) {
            isNumberPrime = false;

    if (isNumberPrime) {
        document.writeln(`${userValue} is a prime number`);
    } else {
       document.writeln(`${userValue} is a not prime number`);



Enter the number: 7
7 is a prime number

Enter the number: 1
1 is neither prime nor composite number.

Enter the number: -11
Negative number cannot be a prime number