Number prime test in JavaScript by creating a custom function?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Create a custom function to test a number is prime or not in JavaScript.

Example

Following is the code −

function checkNumberIsPrime(number) {
   var flag = false;
   for (start = 2; start < number / 2; start++) {
      if (number % start === 0) {
         flag = false;
            break;
      }
      else {
         flag = true;
      }
   }
   return flag;
}
var number = 11;
if (checkNumberIsPrime(number) == true) {
   console.log("The number is prime");
} else {
   console.log("The number is not prime");
}

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo230.js.

Output

The output is as follows −

PS C:\Users\Amit\JavaScript-code> node demo230.js
The number is prime
raja
Published on 03-Oct-2020 14:52:27
Advertisements