Sum all primes while/if help

Hello I was wondering if anyone could help shed light on a issue I’ve been having with my code for the sum all primes exercise. The below effectively doesn’t filter for primes and returns 54

function sumPrimes(num) {
    var primeSeed = []
  for (let i = 2; i <= num; i++){
primeSeed.push(i) 
  }
var optimusPrime = primeSeed.filter(item => {
  let i = item -1
  while(i > 1 && i >= Math.sqrt(item)){
        if(item % i == 0){
    return false;
    i-- 
    }}
  return true;
 })
.reduce((a, b) => a + b)
return optimusPrime
}
sumPrimes(10);

But when the braces are removed from the if statement under the while it runs fine ie. this returns 17

function sumPrimes(num) {
    var primeSeed = []
  for (let i = 2; i <= num; i++){
primeSeed.push(i) 
  }
var optimusPrime = primeSeed.filter(item => {
  let i = item -1
  while(i > 1 && i >= Math.sqrt(item)){
        if(item % i == 0)
    return false;
    i-- 
    }
  return true;
 })
.reduce((a, b) => a + b)
return optimusPrime
}
sumPrimes(10);

Can anyone help me understand why this is?
Thanks!

It looks like the lack of brackets breaks the while loop, which is an infinite loop. So, unless broken out of, the while loop continues forever, and does not yield the result.

1 Like

this part here, in one case it is never executed as it is inside the if statement, i is never reduced, and it becomes an infinite loop. When instead you don’t use brackets then the if statement block is of only one line (the return statement)

1 Like