Check Prime Number using Array Methods

We can also use JavaScript array methods to create a more functional approach. In this approach, we create an array of potential divisors using Array.from and then use the every method to check that none of them divides the number evenly.

Javascript




function isPrime(number) {
    return number > 1 && Array.from(
        { length: Math.sqrt(number) - 1 }, 
        (_, i) => i + 2)
        .every(divisor => number % divisor !== 0);
}
  
console.log(isPrime(5));
console.log(isPrime(4));
console.log(isPrime(11));
console.log(isPrime(21));


Output

true
false
true
false

JavaScript Program to Check Prime Number By Creating a Function

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In this article, we will explore how to check if a given number is a prime number in JavaScript by creating a function.

Table of Content

  • Check Prime Number using for Loop
  • Check Prime Number using Array Methods
  • Check Prime Number using Recursion

Similar Reads

Check Prime Number using for Loop

The basic method to check for a prime number is by using a loop to divide the number by each integer less than its square root....

Check Prime Number using Array Methods

...

Check Prime Number using Recursion

We can also use JavaScript array methods to create a more functional approach. In this approach, we create an array of potential divisors using Array.from and then use the every method to check that none of them divides the number evenly....

Contact Us