Intemediate Algorithm Scripting: Sum All Primes 2

Tell us what’s happening:
The console.log of sumPrimes shows correct answers to all 3 tests, but the system says tests 2 and 3 failed.
Your code so far


let arrPrimes = [2];
function testPrime(num) {// NOT evenly divisible by any in arrPrimes
return arrPrimes.every(item => num % item != 0);
}

function sumPrimes(limit) {
let sum = 2;
let working = true;
let nextNum = arrPrimes[0]; // Start with highest prime so far.
while (working) { // While within limit,
  nextNum++; // add 1 to testable number      
  if (nextNum > limit) { // We are done with sumPrimes:
    working = false; // break out of both functions.
  } else { // The number being tested is within limit, so
      if (testPrime(nextNum)) { // is it a prime?
        arrPrimes.unshift(nextNum); // Yep! Add as arrPrimes[0],
        sum += arrPrimes[0]; // add it to the sum.
      } // Not at next prime yet.
  } // Process next higher number.
}
return sum;
}

console.log(sumPrimes(10));
  **Your browser information:**

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

Challenge: Sum All Primes

Link to the challenge:

ahha!

Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2
1 Like

Thanks, I’ll make that change; I can see how that is an undesirable practice when numbers larger than those in the test cases might be involved.
However, it would be good if the Hints mentioned this, since the fact that my existing code does produce the correct answers was very confusing!

It’s a big theme in the Functional Programming section, but sometimes people forget by the time they make their way to the Algorithms sections.

I know I’ve forgotten how much I’ve forgotten :smiley:

Yes, avoiding global variables was a previous theme; guess I should have picked up on that.

Thanks again!