mtfurlan
mtfurlan

Reputation: 1062

jslint warning "Don't make functions within a loop" only for functions referencing outside variables?

I have two anonymous functions created inside a loop, but jshint only gives a warning when the anon function references a variable not passed to it.

Why is this?

(function(){
  for(var i=0; i<5; ++i){
    var age = 9001;
    //This has a jshint warning, as it uses age
    var cutoffs = [1800,12000].map(function(cutoff){
      return cutoff < age;
    });
    //but this doesn't cause a warning, despite creating a function inside a loop
    var cutoffs2 = [1800,12000].map(function(cutoff){
      return cutoff < 42;
    });
  }
})();

Upvotes: 2

Views: 2203

Answers (2)

Arye Eidelman
Arye Eidelman

Reputation: 1966

Add long as the function executes synchronousy within the loop (before the next irritation) or doesn't reference the counter (i) there won't be any unexpected results.

See http://linterrors.com/js/dont-make-functions-within-a-loop for a full explanation of the issue and a workaround

https://github.com/jshint/jshint/pull/1887#issuecomment-57963322

Just a fleeting thought... why stop here? In fact, the only dangerous loop function is one that uses the loop variables itself inside the function without closing it over.

I get that this is a step in the right direction, but use of outer scope variables isn't what's dangerous here, it's loop variables themselves. We should make this check even MORE lenient.

Upvotes: 0

mtfurlan
mtfurlan

Reputation: 1062

It is just a bad warning that should have been changed.

From the jshint issue I opened:

This warning was initially reported for all functions within a loop. It wasn't until gh-1887 (released in version 2.5.7) that the warning was limited to specific cases according to the bindings around which it closed. The text probably should have been updated at that time, as well.

It will be fixed by jshint pull request 3058, whenever that gets dealt with.

Upvotes: 3

Related Questions