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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *