sindresorhus/eslint-plugin-unicorn

`no-for-loop` breaks on ArrayLike DOM nodes (like `<form>`)

Closed

#1,531 opened on Sep 18, 2021

 (5 comments) (0 reactions) (0 assignees)JavaScript (468 forks)user submission
bughelp wanted

Repository metrics

Stars
 (5,022 stars)
PR merge metrics
 (Avg merge 1d 16h) (399 merged PRs in 30d)

Description

For loops for non-iterable DOM nodes are treated as iterable arrays.

I'm not sure if this is detectable, surely at least some edge cases wouldn't be - but when the variable is populated immediately above the loop it seems at least theoretically feasible.

Affected rule: no-for-loop

Input:

const visibleItems = document.querySelector('.visible');
for (let x = 0; x < visibleItems.length; x++) {
  someFunc(visibleItems[x])
}

Output:

const visibleItems = document.querySelector('.visible');
for (const [x, visibleItem] of visibleItems.entries()) {
  someFunc(visibleItem)
}

As an aside, the fact that the auto-fix depluralizes visibleItems[x] to visibleItem is a very nice touch!

Contributor guide