A loop's body always leaves the loop on its first pass

tx0/ts:loop-runs-oncerecommendedwarningbug

What it finds

``text for (let i = 0; i < items.length; i++) { if (items[i].ok) return items[i]; return null; } ``

A loop whose body always leaves it, with return, throw or break, by the end of the first pass never runs a second time. Usually the exit was meant to go after the loop, or inside a condition.

for, while and do loops are reported when the last statement of their body is a return, a throw or an unlabeled break, and no continue in the body applies to the loop. for-in and for-of loops, which are a known way to take the first entry of a collection, are left alone.

From the rule's source, loop_runs_once.rs.

Example from the rule's tests
export function first(items: { ok: boolean }[]) {  for (let i = 0; i < items.length; i++) {tx0 reports: this loop leaves on its first pass and never repeats    if (items[i].ok) {      return items[i];    }    return null;  }  for (const key in items) {    return key;  }  for (let i = 0; i < items.length; i++) {    if (!items[i].ok) {      continue;    }    return items[i];  }  return undefined;}
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:loop-runs-once" = "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:loop-runs-once] reason="..."

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