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));
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.
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.