how to extract prime numbers from 0 to 1000 in javascript

Here's the code to extract prime numbers from 0 to 1000 in JavaScript using a loop and an array:

index.tsx
// function to check if a number is prime
function isPrime(num) {
  if (num <= 1) {
    return false;
  }
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (num % i === 0) {
      return false;
    }
  }
  return true;
}

// loop to iterate over numbers from 0 to 1000
let primes = [];
for (let i = 0; i <= 1000; i++) {
  if (isPrime(i)) {
    primes.push(i);
  }
}

console.log(primes);
391 chars
23 lines

The function isPrime checks if a number is prime by iterating over numbers from 2 to the square root of the number. If the number is divisible by any of those numbers, it's not prime.

The loop then iterates over all numbers from 0 to 1000 and adds any prime numbers it finds to an array called primes. Finally, the array is logged to the console.

gistlibby LogSnag