is prime in javascript

To check if a number is prime in JavaScript, we can write a function that loops through all the numbers from 2 to the square root of the given number and checks if any of them divide the given number evenly. If no numbers divide the given number evenly, then it is a prime number.

Here's the function:

function isPrime(num) {
  if (num <= 1) return false; // numbers less than or equal to 1 are not prime

  const limit = Math.sqrt(num); // store the square root of the given number

  for (let i = 2; i <= limit; i++) { // loop through numbers from 2 to the square root of given number
    if (num % i === 0) return false; // if any number from the loop divides the given number evenly, then it is not a prime number
  }

  return true; // if no numbers from the loop divide the given number evenly, then it is a prime number
}
527 chars
12 lines

Here's an example usage of the function:

console.log(isPrime(11)); // true
console.log(isPrime(16)); // false
69 chars
3 lines

In the example above, the isPrime function is called with argument 11 which is a prime number, so the output is true. Then, the function is called again with argument 16 which is not a prime number, so the output is false.

gistlibby LogSnag