Sum all prime numbers: weird behavior

Sum all prime numbers: weird behavior
0.0 0

#1

Hi everyone,
I think I solved this challenge but I am experiencing weird behavior and my code isn’t passing FCC tests. When you call the function and pass it a number, it gives the correct results, but if you call the function more than one time, it collects all the results, that is for example the results for sumPrimes(10) and adds it to the results of sumPrimes(977) and gives the total as the result. why? thanks in advance for helping me.
Here’s my code:

function isPrime(number){
      for (i = 2; i <= number; i++){
          if(number % i === 0 && number!= i){
             return false;
          }
       }
      return true;
  }

var newArr = [];
function sumPrimes(num) {
  for (var i=2; i<=num; i++){
    if(isPrime(i) === true){
    newArr.push(i);
  }
}

//console.log(newArr);
var results = newArr.reduce(function(acc, val) {
  return acc + val; });
 console.log(results);
 return results;
}

sumPrimes(977); //73156.

#2

I think it’s most likely the global variable newArr that’s causing it. I don’t remember what the reason for this is, but there have been similar issues like this in the past caused by global variables in the fCC code editor.

Since there is no reason that newArr has to be global, you can simply move it to inside sumPrimes(). If I’m not mistaken, it is often a good idea to scope variables to only the block containing the code that requires it.


#3

that was it!! thanks!!!