Function throws an error in FC but works in jsfiddle and

I’m going through the Intermediate Algorithms section of JS and wrote and tested my code for the Sum All Primes problem. It satisfies the conditions when I test it in jsfiddle and programiz, but FC throws a Reference Error saying that “i is not defined”. Is this a bug? Here’s the jsfiddle Edit fiddle - JSFiddle - Code Playground

function sumPrimes(num) {
   let arr = []
   let count = 1
   let nonPrime = []
   for (i  = 0; i < num; i++) {
       arr.push(count++)
   }
   arr = arr.reverse()
   arr.pop()
   
   for (el of arr) {
       for (let i = 1; i < arr.length; i++) {
           if (el % arr[i] === 0 && el !== arr[i]) {
               nonPrime.push(el)
           }
       }
   }
   return arr.filter(n => !nonPrime.includes(n)).reduce((a, b) => a + b)
}

console.log(sumPrimes(10));

Hi @Montin !

You have actually have to errors where you haven’t defined these variables.

Fix those and the test will pass.

1 Like

Hello, thank you for the reply. But how come the code is working in other code editors?

There is a message pointing out the error in the jsFiddle if you hover your mouse over the yellow underline

1 Like

Thank you, I declared them and it passed the test. Just one more question, is that considered an error on my part or is it just bad practice? Since the code did work, I’m not sure if this is something I can get away with in practice.

Most of the time you want to use ‘strict mode’ where this sort of thing is an error… Otherwise the variables will be automagically declared as var for you, which can sometimes lead to difficult to debug behavior.


Side note, this is a tricky challenge. It’s great that you have passing code, but I’d consider looking at the solutions in the guide to see some ways to make a more efficient approach. This is one of those problems that offers a ton to learn.

2 Likes

I can’t believe I didn’t put ‘let’ before ‘el’ and ‘i’ lol. It dawned upon me just now that that’s what the problem was.

1 Like

Oh yeah, I honestly had 0 hope that I could do it by myself after failing the previous challenge (Fibonacci numbers) miserably. I got the second half of that one but I had to search for the algorithm to get the numbers, so it was a very pleasant surprise nailing this challenge.

These number ones can be like that. Converting from math to code can be tricky.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.