Javascript: Sum All Primes

Hi Guys, could someone help me out with this challenge - my code seems to work for num < 745. So it fails the last test. Not sure where I am going wrong:

function sumPrimes(num) {
 let primesArr = [];
 for (let i = 2; i < num; i++){
  let testArr = [];
  //generate test array for each i value
  for (let j = 2; j < i; j++){
  // test each i value against against its test array
  if (testArr.every(value => i % value !== 0)){
 return primesArr.reduce(((sum, num) => sum + num),0);


Thanks in advance!

Link to Challenge

Welcome to the forums t.pateman2.

Could you please post the link to the challenge in question so that people can help you more easily?

Thanks JeremyLT - That’s done


Rewrite sumPrimes so it returns the sum of all prime numbers that are less than or equal to num.

You are missing one number in your logic!

1 Like

If your code stops working for larger numbers, the most likely answer is that you are running afoul of freeCodeCamp’s infinite loop protection. To save students from crashing their browser with an infinite loop (or infinite recursion), freeCodeCamp tests will exit after a set amount of time. If code is inefficient, it can take long enough to run that it times out before it is done.

All challenges can be solved efficiently enough not to time out, but sometimes it takes some work. It’s often easier to take slow, working code and make it more efficient than try to be perfect from the beginning. It’s also perfectly fine to do research on efficient ways to do things like this. Turning a mathematical approach into code is a good skill to build.

1 Like

Unrelated to passing the challenge - this solution has some serious efficiency concerns that will cause it to take a very long times as num gets big.

A few tips:

  1. Big arrays are slow. Only make arrays of information that you must have and cannot create otherwise.
  2. You don’t need to check if every number less that itself divides the number to know if the number is prime. (The largest possible factor of a number is it’s own square root)

Also, once you get a version that you think works quickly, it would be worth looking at the Sieve of Eratosthenes based approaches.

I did a bit of a write-up on performance of that approach here: JavaScript Performance Measurement & Variability

1 Like

Sugar! ‘or equal to’. Two bloody days! Mother Hubbard…
Well, thanks JeremyLT, i guess that’s why you’re the Dungeon Master.

1 Like

Yup, we’ve all been there. One character bugs are the hardest to find!

software development process meme