The body of a for loop assigns the counter that its head steps

tx0/ts:for-counter-changed-in-bodyrecommendedwarningsmell

What it finds

A for loop that steps its counter in its head and changes it again in its body has two places that decide how it advances. A reader of the head is misled about which iterations run, and an off-by-one is easy to introduce.

The counters are the variables that the update clause of the head assigns, increments or decrements. A write to one of them in the body is reported, unless it is inside a function defined in the body, which may run later.

From the rule's source, for_counter_changed_in_body.rs.

Example from the rule's tests
export function skip(items: string[]) {  for (let i = 0; i < items.length; i++) {    if (items[i] === "-") {      i++;tx0 reports: i is stepped by the loop head and changed again    }  }  for (let j = 0; j < items.length; j += 2) {    items.forEach(() => {      j = 0;    });  }  for (let k = 0; k < items.length; ) {    k++;  }}
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:for-counter-changed-in-body" = "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:for-counter-changed-in-body] reason="..."

tx0 explain tx0/ts:for-counter-changed-in-body shows the same in the terminal. Found a false positive? Report it.