A function created in a loop uses a var counter that the loop keeps changing

tx0/ts:closure-over-loop-variablerecommendedwarningbug

What it finds

A function created in a loop that uses the loop's counter sees the variable, not its value at the time, when the counter is declared with var: for (var i = 0; i < n; i++) setTimeout(() => log(i)) logs n every time. With let each iteration gets a binding of its own and the function sees the value it was created with.

Reported is the first use, inside a function written in the body of a for, for-in or for-of loop, of a variable that the head of that loop declares with var. Functions that run before the loop moves on are left alone: those passed directly to array methods that call them at once, such as forEach, map or filter, and the executor of new Promise.

From the rule's source, closure_over_loop_variable.rs.

Example from the rule's tests
export function schedule(items: string[]) {  for (var i = 0; i < items.length; i++) {    setTimeout(() => console.log(i));tx0 reports: sees i as the loop leaves it  }  for (let j = 0; j < items.length; j++) {    setTimeout(() => console.log(j));  }  for (var k = 0; k < items.length; k++) {    items.forEach(() => console.log(k));  }  let index = 0;  while (index < items.length) {    setTimeout(() => console.log(index));    index++;  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/ts:closure-over-loop-variable" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/ts:closure-over-loop-variable] reason="..."

tx0 explain tx0/ts:closure-over-loop-variable shows the same in the terminal. Found a false positive? Report it.