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?
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.The second code doesn't bind to the same
tableeach time.letcreates a new scope oftablefor each iteration of the loop. If you had usedvar tableinstead oflet table, they would have shared scope and they would all use the last value oftable(see JavaScript closure inside loops – simple practical example)