By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
Notification Show More
Latest News
Passing a JavaScript Value Between HTML Pages
Passing a JavaScript Value Between HTML Pages
JavaScript
Compare Objects in an Array
JavaScript Problem: Compare Objects in an Array
JavaScript
Switching Name Order Using Capturing Groups in Regular Expressions
Switching Name Order Using Capturing Groups in Regular Expressions
JavaScript
Shuffling an Array
JavaScript Problem: How to Perform Shuffling an Array
JavaScript
Create a Non-duplicated Collection
JavaScript Problem: Using Set to Create a Non-duplicated Collection
JavaScript
Aa
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript Program > Write a Program to Check If a Number is a Prime Number or Not in JavaScript
JavaScript Program

Write a Program to Check If a Number is a Prime Number or Not in JavaScript

Rocoderes
Last updated: 2022/09/09 at 3:20 PM
Rocoderes
Share
6 Min Read
Write a Program to Check If a Number is a Prime Number or Not in JavaScript

In this article, we will make a program to check if a number is a prime number or not. So basically, we will have an input field in which we will get the number from the user then we also have a button, by clicking it we will run this program and get the result for the input. We will make this in 2 ways, one with pure JS code and another one with the help of little HTML code.

Contents
What is a Prime Number?Using Pure JS CodeUsing HTML ElementOutputYou may also like:

What is a Prime Number?

So before going to the code, let’s understand the logic first. Prime numbers are those numbers that are only divisible by 1 and the number itself. For example, 13 is only divisible by 1 and 13 only. In this program, we will just get the remainder to compare with 0. So the remainder will be 0 only if we divide the number by 1 and 13.

Using Pure JS Code

So firstly, we have made an HTML markup in order to run JS code. In that, we have a script tag for JS code, Here, we have added a variable x with the prompt message to get the input value. Then we have checked a condition to where the number is 1, if yes then we have printed a message that it is not a prime nor composite. If not, then we have checked another condition to check where the provided number is below 1 then we have printed that the number is not a prime.

If both conditions are false, then we have added an else part, in which we have added a for a loop. In this loop, we have declared a variable ‘i’ with an initial value of 2. This loop will run to the provided value, like if we provide 10 then 9 will be the last value for ‘i’. In this loop, we will check the condition where if the number returns 0 remainders, if yes then it won’t be a prime number. And if no then we will again loop this with an increased value of ‘i’ to check again the same condition.

Here if every time the else part gets executed then the number will prime. If not then it is not a prime number.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script type="text/javascript">
      var x = prompt("Please Enter The Number:");
      if (x == 1){
        document.write(`${x} is neither prime not composite`);
      }
      else if(x < 1){
        document.write(`${x} is not a prime number`);
      }
      else{
        for(var i=2; i < x; i++){
          if(x % i ==0){
            var res = `${x} is not a prime number`;
          }
          else{
            var res = `${x} is a prime number`;
          }
        }
        document.write(`<h1> ${res} </h1>`);
      }
    </script>
  </body>
</html>

Using HTML Element

In this, we will apply the same logic, but we will get the value from the user inside the input field which is an HTML element. Also, we will provide a button on which we need to add an event listener to get the output. As we can see, we have some increased code, but it is necessary to learn in order to learn JavaScript and its events.

So here we just fetched the value from the input value from the user using document.querySelector().value the method. This is useful when we need to manipulate or update an element from the DOM. On the button, we have added an event listener for the click event, in which we will run a function when it gets clicked. You can see we have created a function and put the whole logic in it.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="number" />
    <button onclick=result>Result</button>
    <script type="text/javascript">
      function result(){
        var x = document.querySelector("input").value;
        if (x == 1){
         document.write(`${x} is neither prime not composite`);
        }
        else if(x < 1){
          document.write(`${x} is not a prime number`);
        }
        else{
          for(var i=2; i < x; i++){
            if(x % i ==0){
              var res = `${x} is not a prime number`;
            }
            else{
              var res = `${x} is a prime number`;
            }
          }
          document.write(`<h1> ${res} </h1>`);
        }
      }
    </script>
  </body>
</html>

Output

Write a Program to Check If a Number is a Prime Number or Not in JavaScript

You may also like:

  • How to Check If a Number is Positive, Negative, or Zero
  • How to Convert Kilometers to Miles and Celsius to Fahrenheit
  • How to Add Two Numbers, Swap Two Numbers And Find Square Root in JavaScript
  • Write a program to Check if a Number is Odd or Even in JavaScript

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

TAGGED: programs
Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Posted by Rocoderes
Rocoderes is a blog you can learn HTML, CSS, JavaScript, React Js and Python along with creative coding stuff and free source code files.
Previous Article Write a program to Check if a Number is Odd or Even in JavaScript Write a program to Check if a Number is Odd or Even in JavaScript
Next Article How To Find map length in JavaScript How To Find map length in JavaScript
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

Computing Fibonacci Sequence in JavaScript

Computing Fibonacci Sequence in JavaScript

January 12, 2023
Swap Two Numbers Without A Third Variable

How to Swap Two Numbers Without A Third Variable in JS

December 12, 2022
Armstrong Number

How to Find an Armstrong Number Using JavaScript

September 23, 2022
Print The Table

How to Print The Table of Any User Defined Number Using Function

September 22, 2022
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?