You are currently viewing How to Print Prime Numbers in JavaScript

How to Print Prime Numbers in JavaScript

Print prime numbers in Javascript

prime number is a number that can be divided exactly only by itself and 1. for ex: 3,5,7,9,11, 13,17, etc.., If we want to print prime numbers in javascript, we must use for loop.

Example code

//input the higher number
const higher number = parseInt(prompt('Enter number: '));
console.log(`The prime numbers between 1 and ${higherNumber} are:`);

//creating for loop from 0 to user input number
for (let i = 1; i <= higherNumber; i++) {
let flag = 0;

// looping through 2 to user input number
for (let j = 2; j < i; j++) {
if (i % j == 0) {
flag = 1;
} }

// if number greater than 1 and not divisible by other numbers
if (i > 1 && flag == 0) {
} }


  1. In the above code, we have to get the input ‘higherNumber’ for the ending value of the loop.
  2. Then we created for loop and inside it, we initialized the flag variable to 0, then we create another loop inside it.
  3. We check the condition (i%j==), if the condition is true we assigned a flag to 1, else it terminates the loop.
  4. Finally, we check the condition (i<1 && flag == 0), if the conditions is true. The prime number is printed.

Leave a Reply