# JavaScript Program to Check Prime Number

You are Here:

## What is Prime Number?

A positive integer that is divisible only by itself and 1.

Tips: It is recommended to use our online Prime Numbers calculator for better understanding.

## Examples

The following table provides few examples of prime numbers.

NumberDivisorResult
131, 13Prime Number
151, 3, 5, 15Not a Prime Number
471, 47Prime Number

## Using for loop

In the following example, we will check whether the given number (7) is a Prime number or not using for loop.

### Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <h1>JS Prime Number</h1> <script> var num = 7; var i = 1; var count = 0; for(i=1; i<=num; i++) { if(num % i == 0) count++; } if(count == 2) document.write(num +" is a prime number"); else document.write(num +" is not a prime number"); </script> </body> </html>

## Using while loop

In the following example, we will check whether the given number (7) is a Prime number or not using while loop.

### Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <h1>JS Prime Number</h1> <script> var num = 7; var i = 1; var count = 0; while(num >= i) { if(num % i == 0) count++; i++; } if(count == 2) document.write(num +" is a prime number"); else document.write(num +" is not a prime number"); </script> </body> </html>

## Using do while loop

In the following example, we will check whether the given number (7) is a Prime number or not using do while loop.

### Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <h1>JS Prime Number</h1> <script> var num = 7; var i = 1; var count = 0; do { if(num % i == 0) count++; i++; }while(i<= num); if(count == 2) document.write(num +" is a prime number"); else document.write(num +" is not a prime number"); </script> </body> </html>

## Prime Numbers between the Given Range

In the following example, we will find all the Prime numbers between 1 and 20.

### Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <h1>JS Find All Prime Numbers</h1> <script> var start = 1; var end = 20; var count = 0; var i = 1; document.write("The prime numbers between "+start+" to "+end+":<br>"); for(start=start; start<=end; start++) { for(i=1; i<=start; i++) { if(start % i == 0) count++; } if(count == 2) document.write(start +", "); count = 0; } </script> </body> </html>

## Prime Number or Composite Number

In the following example, we will check whether the given number (12) is a Prime number or Composite number.

### Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <h1>JS Prime Number or Composite Number</h1> <script> var num = 12; var i; var count = 0; for(i=1; i<=num; i++) { if(num % i == 0) count++; } if(count == 2) document.write(num +" is a prime number"); else document.write(num +" is a composite number"); </script> </body> </html>

## Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.