function to check if a number is prime in javascript

To check if a number is prime in Javascript, you can use the following function:

index.tsx
function isPrime(num) {
  // 1 is not a prime number
  if(num === 1) return false;
  
  // 2 and 3 are prime numbers
  if(num === 2 || num === 3) return true;
  
  // other even numbers are not prime numbers
  if(num % 2 === 0) return false;
  
  // check odd numbers up to the square root of the given number
  for(let i = 3; i <= Math.sqrt(num); i += 2) {
    if(num % i === 0) return false;
  }
  
  // the number is prime
  return true;
}
443 chars
19 lines

This function takes a number as an argument and returns true if it is a prime number and false otherwise.

The function first checks if the number is equal to 1, which is not a prime number. It then checks if the number is equal to 2 or 3, which are prime numbers. If the number is even, it is not a prime number. If the number is odd, the function checks odd numbers up to the square root of the given number. If the number is divisible by any of those odd numbers, it is not a prime number. If the function has not returned false by this point, the number is prime and the function returns true.

gistlibby LogSnag