Categories
JavaScript Answers

How to check if a number is prime in JavaScript?

Spread the love

Sometimes, we want to check if a number is prime in JavaScript.

In this article, we’ll look at how to check if a number is prime in JavaScript.

How to check if a number is prime in JavaScript?

To check if a number is prime in JavaScript, we can use a loop.

For instance, we write

const isPrime = (num) => {
  for (let i = 2, s = Math.sqrt(num); i <= s; i++) {
    if (num % i === 0) {
      return false;
    }
  }
  return num > 1;
};

to define the isPrime function.

In it, we loop from 2 to the square root of num.

In the loop body, we check if num can be evenly divisible by i with num % i === 0.

And if it’s true, we return false since it’s not prime.

If it’s evenly divisible by nothing, we return true.

Conclusion

To check if a number is prime in JavaScript, we can use a loop.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.