Why does jshint warn of calling functions from a function declared within a loop?

33 Views Asked by At

The following code

function foo () {}

let data = [];

for (let x of data)
{
  let bar = function ()
  {
    foo ();
  };
}

causes this warning in jshint

Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (foo)

I am aware that Javascript has unintuitive rules for binding variables to functions created in a loop. For example (if I've got this right) the following code causes each function object to bind to the same table

for (let table of document.getElementsByTagName ("table"))
{
  table.my_function = function ()
  {
     do_something_with (table);
  };
}

I think jshint is treating these two cases as equally suspicious. But they look different to me. Is this warning something to take seriously, or is jshint being overly paranoid?

1

There are 1 best solutions below

5
Barmar On

The function has no references to x, so there's no need to create a new function each time through the loop. Declare the function once and assign it to each array element.

for (let x of data)
{
  x.bar = foo;
}

The second code doesn't bind to the same table each time. let creates a new scope of table for each iteration of the loop. If you had used var table instead of let table, they would have shared scope and they would all use the last value of table (see JavaScript closure inside loops – simple practical example)