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
Contact Us