Does "Don’t make functions within a loop" always apply?

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

  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.

Usually is considered bad practice to create functions inside a loop because they create a closure, so it’s more error prone and “less intuitive” at a first glance.

In your case you are executing an action (method) if a certain condition is met.
That’s a pretty standard behaviour :slight_smile:

Just for clarity, a callback is generally considered a function you call after a function to keep executing an action, in your case you are not calling nor creating any new function.

1 Like