find prime number in javascript

Here is an example code to find whether a given number is prime or not in JavaScript using an iterative approach:

index.tsx
function isPrime(n) {
  // If input is less than 2, it's not prime
  if (n < 2) {
    return false;
  }

  // Check for divisibility from 2 to square root of n
  for (let i = 2; i <= Math.sqrt(n); i++) {
    if (n % i === 0) {
      return false;
    }
  }
  
  // If none of the above conditions match, the number is prime
  return true;
}
341 chars
17 lines

To use this function, simply pass a number to it as an argument and it will return true or false depending on whether the number is prime or not:

index.tsx
console.log(isPrime(5)); // true
console.log(isPrime(10)); // false
68 chars
3 lines

gistlibby LogSnag