JavaScript Program to check Prime number

A prime number is a positive number that is divisible by 1 and itself only. Some of the first few prime numbers are 2, 3, 5, 7, and 11.

A prime number is a positive number that is divisible by 1 and itself only. Some of the first few prime numbers are 2, 3, 5, 7, and 11.

1, 0 and any negative numbers are not prime.

Since a number is always divisible by 1 and itself, we need to check whether the numbers falling between these two, can divide the given number or not. If yes then it’s not a prime number, if not then it’s a prime number.

Example

<script>
    function checkPrime(num) {
      let isPrime = true;
      if (num <= 1) {
        isPrime = false;
      } else {
        for (let i = 2; i < num; i++) {
          if (num % i === 0) {
            isPrime = false
            break;
          }
        }
      }
      if (isPrime) {
        console.log(num + ' Prime')
      } else {
        console.log(num + ' Not Prime')
      }
    }

    const input = [1, 2, 11, 15, -10, 37]
    input.forEach(value => checkPrime(value))
</script>

Output

1 Not Prime
2 Prime
11 Prime
15 Not Prime
-10 Not Prime
37 Prime