I’ve seen many examples of how declaring functions in a for loop will bite you later. The examples all make sense - expecting 1,2,3 but getting 3,3,3 - I get that.
Does that really apply to a situation like below? Every time I use a callback to one of the array methods inside a trivial loop the linter balks. I can’t see how in this specific case it could ever fail me. Am I missing something?
Spoils a solution to Sum All Primes
function sumPrimes(num) {
let primes = [2]; //first prime
for (let i = 2; i <= num; i++) {
if (primes.every(prime => i % prime)) { //<-- this callback here
primes.push(i);
}
}
return primes.reduce((acc, el) => acc + el);
}
The function is anonymous. Not saved to a variable. Nothing async. It is not accessible outside of the for loop. I just can’t see where I’ll ever get the wrong value of i.
I’ve always taken it on faith that this was wrong because the linter said so. I tried Googling this specific case but I keep finding variations of the same classic example that doesn’t seem to apply here.