How to useArray Methods in Javascript
We can also use JavaScript array methods to make the code more concise and functional. In this approach, we use the Array.from
method to create an array of numbers in the given range, the filter
method to keep only the prime numbers, and the forEach
method to log them.
Javascript
function isPrime(number) { return number > 1 && Array.from( { length: Math.sqrt(number) }, (_, i) => i + 2) .every(divisor => number % divisor !== 0); } function displayPrimes(start, end) { Array.from({ length: end - start + 1 }, (_, i) => i + start) .filter(isPrime) .forEach(prime => console.log(prime)); } // Driver code let num1 = 500; let num2 = 600; displayPrimes(num1, num2); |
503 509 521 523 541 547 557 563 569 571 577 587 593 599
JavaScript Program to Display Prime Numbers Between Two Intervals Using Functions
Prime numbers are natural numbers greater than 1 that are only divisible by 1 and themselves. In this article, we will explore how to create a JavaScript program to display all prime numbers between two given intervals using functions.