Sum All Primes in Java Script

Tell us what’s happening:

Hi, I’m totally confused by this challenge. As I understood, I only counted primes so far (is this correct, btw?). Could you also advise me how to count them all please?

Your code so far


function sumPrimes(num) {
  var primes=[];
 if(num < 2) 
 return false;

for (var i = 2; i <= num; i++) {
 if(num%i==0)
            return false;
    }
    return true;
    
for(var j = 0; j <= num; j++){
    if(isPrime(i))
    primes.push(i);
}
return primes; 
}
sumPrimes(10);

Your browser information:

Chrome Version 75.0.3770.142 (Official Build) (64-bit)

Link to the challenge:

“sum” doesn’t mean count

Bit by bit here:

var primes=[];

You’re looping over things in this function and adding up. I’m not sure why you feel you need to put them in an array, but anyway

if(num < 2) return false;

Why false? This isn’t a particularly good thing to return, but I don’t think this gets tested so whatever.

for (var i = 2; i <= num; i++) {
 if(num%i==0) return false;
}
return true;

So when we get to this bit of code, this loop starts, and if it finds an even number, the function exits and returns false. Otherwise it exits as false.

I assume you meant to wrap that bit of code in a function called isPrime, because:

for(var j = 0; j <= num; j++){
 if(isPrime(i)) primes.push(i);
}

 return primes; 
}

sumPrimes(10);

Otherwise that piece of code doesn’t make sense.

Also, watch formatting consistently, the code is very difficult to read because the spacing and new lines seem random. And if you really really want to miss off brackets on if statements, at least put the expression on the same line.