Sum All Primes Help

Tell us what’s happening:

Please explain why my code is not returning result. Thank you.

Your code so far


let result=0;

function sumPrimes(num) {
  
  function isPrime(x){
    
    for (let i=2;i<x;i++){
      
      if (x%i==0&&x!==i ){
        
        return false;
      }

    }
    return true;
  }
  
  
  

  if (isPrime(num)){
    result+=num;
  }
  if (num==2){ 
    
    console.log(result)
    return result;
    
  }
  
  sumPrimes(num-1);
  
  
   
}

sumPrimes(977);


Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36.

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

1 Like

You have at least three distinct problems. (The first one I list isn’t technically a deal breaker, but it will help you debug the other two.)

The “output” you are seeing is from your console.log not the actual return value. I suggest you fix this FIRST as it will make solving the other problems a whole lot easier.

The second problem is that you aren’t actually returning anything from sumPrimes. So, I’d tackle that next.

And your result is global, which is causing subsequent runs to start at the wrong spot. But I wouldn’t deal with that until you’re returning and logging out the current results of sumPrimes.

I also had a hard time reading your code the way it was formatted. :frowning: Here’s a version that was easier for me to read, with some comments that might be useful,

let result = 0; // having this on the global context is causing you problems

function sumPrimes(num) {
  
  function isPrime(x){
    for (let i = 2; i < x; i++){
      if (x % i == 0 && x !== i ){
        return false;
      }
    }
    return true;
  }
  
  if (isPrime(num)){
    result += num;
  }

  if (num == 2){
    // I think this console.log was throwing you off
    // console.log(result) 
    return result;
  }
  
  sumPrimes(num-1); // you need to return something here ;-)
}

// Logging out like this will let you see what's actually being returned
console.log(sumPrimes(10))
console.log(sumPrimes(10))