Sum All Primes (i variable doesn't seem to increase)

Tell us what’s happening:
Hello, everyone! This is my first post here for help because I always try to research a lot to find my answer but for this one I’m stuck.

You can see my code below. (Ignore that I’m printing to the console rather than returning the statement… I did that just so I can see what’s going on better.)

The part that I’m really stuck on is why it seems the i variable in my loop keeps getting stuck at 2 and not increasing to check the other factors. Any help, hints, anything at all would be much appreciated!

Thank you!

Your code so far


function sumPrimes(num) {
  let arr = [];
  var i;
  for (let i = 2; i <= num; i++){
    arr.push(i)
  }
  console.log(arr.filter(x => {for (i = 2; i <= x; i++){
    console.log(i);
    if (x % i == 0 && x != i){
      return false
    }
    else {return true};
  }
  }
  ).reduce((accumulator, currentValue) => {return accumulator + currentValue}))
};
sumPrimes(10);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes/

your if statement has 2 returns in it and the return kills the for loop immediately.

1 Like

Thanks a lot! I’ve got it working now thanks to your little nudge. :smiley: Much appreciated!!

1 Like