A number is a prime if it is not divisible by other primes lower than the number in question.
So this builds up a primes
array. Tests each new odd candidate n
for division against existing found primes
lower than n
. As an optimization it does not consider even numbers and prepends 2
as a final step.
var primes = [];
for(var n=3;n<=100;n+=2) {
if(primes.every(function(prime){return n%prime!=0})) {
primes.push(n);
}
}
primes.unshift(2);